iiYO Community

Full Version: Set variable from extension
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

I'm writing an extension and I'm struggling at setting a variable.

Let say that my xml has the variable $my_var, or even a global variable $$my_var

<line s="n">
    The value of global variable my_var is: {$$my_var}

How can I set the value for this variable in my extension?

Hi kodokumatt,

welcome to the forums!

Setting a variable from JavaScript is a little different depending on whether you want to have a local or a global variable (apologies for the confusing names; I should've named them 'variables' and 'persistent variables' instead).

If you want to set a 'global' variable, you can use the globalVars object which is a part of the interpreter instance:

game.interpreter.globalVars.set("myVar", "foo");
game.interpreter.globalVars.get("myVar"); // "foo"

The 'local' variables are just a plain JavaScript object that is saved as is for each savegame:

game.interpreter.runVars["myVar"] = "foo";

The difference between the 'global' vars and the 'local' vars is that a 'local' variable is only available in the current playthrough of a game. All 'local' variables are replaced when you load a savegame, whereas  'global' variables are the same no matter what savegame you are using. The 'global' variables are meant to be used for meta information like "the player has finished the game 2 times."

The 'game' variable you see in the example above is the Game instance created in the index.html file. You will have to obtain a reference to it in your extension by either adding some code to the JavaScript in the index.html file or by listening to the "wse.game.constructor" event on the global bus:

using("WSE").run(function (WSE) {
   WSE.subscribe("wse.game.constructor", function (data) {
       var game = data.game;
       // ...

Hope this helps and good luck with your game! Smile
Thank you! It helped a lot!