From your answer to my comment, I'm assuming you're keeping the QScriptValue myvar
instance around, and look at it after calling evaluate()
:
QScriptEngine e;
QScriptValue myvar( 1.0 );
e.globalObject().setProperty( "result", myvar );
e.globalObject().setProperty( "anotherVar", QScriptValue( 14 ) );
const QScriptValue s = e.evaluate( "result = anotherVar + 7;" );
qDebug() << s.toVariant();
qDebug() << e.globalObject().property("result").toVariant();
qDebug() << myvar.toVariant();
This will print 2x "QVariant(double,21)" and once "QVariant(double,1)". That is expected behaviour, here's why:
In JavaScript, everything is an object, and you are only dealing with references to objects, not the objects themselves (if you know Java, this is similar to int
vs. Integer
). So, what the assignment result = anotherVar + 7;
does is replace the object represented by myvar
as the global object's "result" property with the object that results from the expression anotherVar + 7
. Meanwhile, the QScriptValue myvar
still references the (old) object, which otherwise would be up for grabs by the garbage-collecter at this point.
About the addition of a=1
to fix the problem: I can't reproduce that here. The first debug statement prints the value of a
, of course, but the second and third are unchanged.
The solution to your problem, therefore, is to always re-get the "result" property from the engine whenever you need it (using engine.globalObject().property("result")
), or—in other words—QScriptValue doesn't track assigments.
If you do want to track assignment, you need to turn it into a method call: Implement result
as a custom class with an assign()
method, and replace assignment (=
) with result.assign( anotherVal + 7 );
.