QScriptEnging::evaluate() returning value



  • Morning!
    I noticed the following trouble using Qt scripts: when I call QScriptEngine::evaluate("1 + 2") I get a number (isNumber() == true) as expected, but calling QScriptEngine::evaluate("return 3") returns unknown QScriptValue that cannot be converted to a number. Can I use return-operand in my script code or not?



  • bq. QScriptEngine::evaluate(“return 3”)

    Have you ever seen script, with body:
    @
    return 3;
    @

    Try to evaluate this one:
    @
    function a() { return 3; }
    a();
    @
    I believe, it will return number. Because variant #1 - it's invalid code (E: return operator outside of function) - "return" can be used only in function.

    bq. Can I use return-operand in my script code or not?

    Yes, you can! But in function, only in function of your script!

    In my opinion, you should learn ECMAscript (JavaScript) syntax ;).



  • Ok...and if I have a complex calculation @var a = 1, b = 2;
    var c = a + b;
    @

    and need var c to be returned? Should I use something like

    @
    function result(var c) {return c;}
    result(c);
    @

    It's a little bit rough.



  • I will give you an example.

    script.js
    @
    function pF( number ) {
    return sqrt(number);
    }

    function pR( number ) {
    return number*number;
    }

    if( pR( pF(25) ) == 25) {
    print("I am Qt Script PRO!");
    }
    @

    mainwindow.cpp
    @
    //...
    QString src = scriptFile.readAll();
    QScriptValue a = engine.evaluate(src);
    if(a.isString())
    qDebug() << a.toString();
    //...
    @

    It will print to debug log: "I am Qt Script PRO!".


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.