PDA

View Full Version : QSA: loading scripts at runtime



seneca
15th February 2006, 15:19
I came across the problem that there is no convenient way to load scripts at runtime. What I first tried was to do it this way:


eval(File.read('foo.qs'));
foo();

foo.qs:

function foo()
{
debug('hello from foo()');
}

Basicly this would work, unfortunately code in eval is not evaluated at global scope, so foo() is unknown after eval() and thus cannot be used. The solution tor the problem is to load the file in C++ and call QSInterpreter::evaluate to process the file. Since there is no convenient support for doing this, I have created a objectfactory as solution (see attachment).

Usage:

To use the script class add it to your interpreter with:


#include "qsscriptfactory.h"
...
interpreter->addObjectFactory(new QSScriptFactory);
...

Then you can use it in your scripts as:

Script.load(code, scriptname, multiple = false);

Load script code from a string in 'code'.
'scriptname' is mandatory and must be unique for distinct scripts.
'multiple' false = ignore attemts to load same script twice. true = allow multiple loading of same script.

Script.loadFile(filename, multiple = false);

Load script from file 'filename'.
'multiple' false = ignore attemts to load same script twice. true = allow multiple loading of same script.

Example:

Script.loadFile('foo.qs'); // load/evaluate script in file foo.qs

Enjoy!