c++qtqtscript

Access values created by QScriptEngine on heap?


[Question]

Suppose we feed QScriptEngine with the following script:

var foo = 1;
var bar = 2;
foo + bar

by QScriptEngine::evaluate(), we'll get a QScriptValue returned which can be translated back into int equal to 3.

On the other hand, if we feed QScriptEngine with the script:

var foo = 1;
var bar = 2;

Then how can we access the values of foo and bar created by the script on heap?

[Example]

enter image description here

Take MATLAB (Python IDLE is the same) as an example. I can read the script file and the variables created by script will still be available to command prompt.

I am thinking about doing the same thing in Qt:

  1. Read the script file to QString
  2. Call QScriptEngine::evaluate() to evaluate the QString

But I can't figure out how to get those var created by the script.

P.S. The script could be very complicated and not just contend variables only, I just try to make the question simpler.


Solution

  • If variables are global then they're accessible in the global object (through globalObject() method). From documentation:

    ...Non-local variables in script code will be created as properties of the Global Object, as well as local variables in global code.

    In short you have to obtain global object and then iterate through its properties to read their values with property() method (please note that you'll have to only variables from your script):

    QScriptValueIterator it(engine.globalObject());
     while (it.hasNext()) {
         it.next();
         qDebug() << it.name() << ": " << it.value().toString();
     }