PDA

View Full Version : QtScript evaluation question



QPlace
22nd October 2009, 04:46
I started to learn QtScript, creating following classes:


template <typename T> class Scriptable
{
public:
Scriptable() {}
static void registerWithScript(const char* scriptObjName, QScriptEngine& scriptengine)
{
T* t = new T();
QScriptValue obj = scriptengine.newQObject(t, QScriptEngine::ScriptOwnership);
scriptengine.setDefaultPrototype(qMetaTypeId<T>(),obj);

QScriptValue testCtor = scriptengine.newFunction(testConstructor, obj);
scriptengine.globalObject().setProperty(scriptObjN ame, testCtor);
}
private:
static QScriptValue testConstructor(QScriptContext* /* context */,
QScriptEngine *interpreter)
{
return interpreter->toScriptValue(T());
}
};


class test : public QObject, public QScriptable, public Scriptable<test>
{
Q_OBJECT
Q_PROPERTY(int val READ val WRITE set)
public:
test (int i = 0) : _i(i) { }
test (const test& another) : _i(another._i){}
virtual ~test () {}
void set(int i)
{
_i = i;
}
int val()
{
return _i;
}

private:
int _i;
};
Q_DECLARE_METATYPE(test)

Then I wrote two short scripts:
Script A:

var t = new test()
t.val = 15
t.val = t.val + 7

and Script B

var t = new test()
t.val = 15
var m = new test()
m.val = 20
t.val + m.val
I run into following problem:
When I execute the script A – everything works fine, script returns 22 as I expect.
But when I execute script B it retuns 40, instead of expected 35. It appears as if variable “t” is replaced with “m” and therefore it returns double of whatever I assign to m.val and "t" is lost.

Below is what I do to run the script:

QString script = ui.txtRequest->toPlainText(); // script text
QScriptEngine interpreter;
test::registerWithScript("test", interpreter);
QScriptValue result = interpreter.evaluate(script);

Any advice is greatly appreciated