QScriptEngine and some script.



  • I have two scripts: script1 and script2

    How I call function from script2 in script1?

    // script2
    
    function f() {
        ...
    }
    
    ...
    
    // script1
    
    script2.f()


  • I could be wrong but I'm not sure this can be done in the sense you are thinking in...

    To my understanding a QScriptEngine is an environment that runs the current script and manages variables and other information about the running script.

    To execute a script in another file you have three choices I think:

    1. Instantiate another QScriptEngine, load the script and run it in that QScriptEngine. You might be able to get fancy and used some shared memory to pass data back and forth.

    2. Load and run the new script in your current script engine. This would of course close out your current script and I'm not even sure how you'd do this... You'd have to stop evaluation of the current script, load the new one and begin execution of it. It could be tricky.

    3. Include the other script in your first one. I have not investigated this directly myself as of yet but the idea would be to like C++ have some form of an include statement which simply at execution time loaded in the other script so it became part of your source. I have not looked at ECMA to see if there is an include statement but you could fool it by processing your script yourself just prior to execution and manually loading in the other script before you pass the whole thing to QScriptEngine.

    I'm hoping someone with more experience can illuminate which of these is the right way to go. I am going to be looking at script inclusion myself as in my current app we are accumulating a lot of small little scripts to do specific things. It would be nice to reuse those.

    Lastly you do know that you can have "functions" in scripts right? If calling script 2 is difficult you could simply paste the entire script into your first script and call it as a function:

    // Script 1:
    // Do some stuff
    // Do more stuff
    
    // Now call the function from script 2
    script2f();
    
    // From script 2:
    function script2f()
    {
      // Do script 2 stuff here
    }

Log in to reply
 

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