CopperSpice API
1.9.1
|
CsScript extensions can make additional functionality available to scripts evaluated by a QScriptEngine. Extensions are imported by calling the QScriptEngine::importExtension() function.
There are three ways to create an extension:
The (dot-qualified) extension name is used to determine the path (relative to the application's plugin path) where QScriptEngine will look for the script file that will initialize the extension; if a file called init.js
(usually located in [application plugin path]/script/foo/
) is found in the corresponding folder, its contents will be evaluated by the engine when the extension is imported. As an example, if the extension is called "foo.bar.baz"
, the engine will look for init.js
in foo/bar/baz
. Additionally, before importing "foo.bar.baz"
, the engine will ensure that the extensions "foo"
and "foo.bar"
are imported, locating and evaluating the corresponding init.js
in the same manner (in folders foo
and foo/bar
, respectively).
The contents of init.js
are evaluated in a new QScriptContext, as if it were the body of a function. The engine's Global Object acts as the this
object. The following local variables are initially available to the script:
"foo.bar.baz"
). setupPackage()
with extension
as argument; e.g. setupPackage("foo.bar.baz")
would ensure that the object chain represented by the expression foo.bar.baz
exists in the script environment. (This function is semantically equivalent to QScriptExtensionPlugin::setupPackage().) An example of a simple init.js
:
QScriptEngine will look for a QScriptExtensionPlugin that provides the relevant extension by querying each plugin for its keys() until a match is found. The plugin's initialize() function will be called after the relevant init.js
(if any) has been evaluated.
Continuing with the example of our imaginary extension "foo.bar.baz"
, the following steps will be performed by QScriptEngine::importExtension():
foo/__init__.js
is evaluated. "foo"
in its list of keys is found, its initialize() function is called with "foo"
as key. foo/bar/__init__.js
is evaluated. "foo.bar"
in its list of keys is found, its initialize() function is called with "foo.bar"
as key. foo/bar/baz/__init__.js
is evaluated. "foo.bar.baz"
as key. When an extension is compiled and linked into your application as a static plugin, CsScript will look for the optional init.js
script in a resource, prefixed by :/qtscriptextension
. For example, if the extension key is "foo.bar", CsScript will evaluate the contents of the file :/qtscriptextension/foo/bar/__init__.js
, if it exists. If the resource is built into the plugin you may need to use the Q_INIT_RESOURCE() macro to initialize the resource before importing the extension.