How should I implement scripting functions in the following scenario?



  • Hey everyone,

    Lets say that I have class that defines a simple method called
    convertFunction(int a, int b)

    This class lets say simply adds the two variables a and b and returns the resulting value plus some other constant.

    What I want to do is at a later date using the script engine to alter that constant (this function could be used for conversions for example).

    So if originally my function given a=2, b=3 returned 2+3+5 I now want for whatever reason to write a script that will alter this and instead return 2+3+6.

    At first I thought checking if the script (I would have to give it a particular name) existed, and if yes then I would override the operations performed in convertFunction and use instead the value returned by the script.

    This though seems not the best of ideas as it seems very rigid.

    What do you believe would be the best architecture that would help me achieve something similar?


  • Moderators

    Hi,

    Have you considered using a scripting engine? See "QJSEngine":http://doc.qt.io/qt-5/qjsengine.html



  • I do use a script engine, I have done many tests, like automatically reading and executing scripts or using defaultPrototypes and a number of other things.

    What I ask here is for a way to structure and organise my code so as to be able to alter functions located inside various classes in the way I described using the script engine. Or to put it in a better way, how can I ignore the script if does not exists and keep my functions output, or how can I ignore the function if the script does exist.


  • Moderators

    Hmm... I don't fully understand what you want to achieve. What kind of "scripting" do you do? Can you give an example of a "script" which affects your function?

    Anyway, read up on functors and see if those are what you want.

    [quote author="ealione" date="1422968607"]This class lets say simply adds the two variables a and b and returns the resulting value plus some other constant.

    What I want to do is at a later date using the script engine to alter that constant[/quote]In this example, the easiest way is to store the constant as a member variable in your class. Update the variable to change the output of convertFunction().

    [quote author="ealione" date="1422970260"]how can I ignore the script if does not exists and keep my functions output, or how can I ignore the function if the script does exist. [/quote]It kind of sounds like you don't need to modify your function, you just need simple branching:
    @
    int result;
    if (scriptExists)
    result = scriptValue;
    else
    result = convertFunction();
    @


Log in to reply
 

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