How to access variables in Javascript?

I’m trying to access scene variables in Javascript, I have tried all the classes and methods from the documentation related to variables in all possible way but I keep getting “undefined” error message. :frowning:

Anybody could write a simple example of how to get the value of a variable in JS?
Thanks.

Just in case, the GDJS Runtime API is here: http://4ian.github.io/GD-Documentation/GDJS%20Runtime%20Documentation/ (maybe some methods are missing)

Both “runtimeScene.getVariables()” and “runtimeScene.getGame().getVariables()” return a VariablesContainer object (the first one return the list of scene variables, the second one the global variables, objects has this method too).

As you can read in the API, the VariablesContainer has a method “get(variable name)” to get a GD Variable object. Finally, the Variable object has the methods “getAsNumber()” and “getAsString()” to return the “raw” values.

So, this code should return the numerical value of the scene variable “MyVar”, and save it in “n”:

var n = runtimeScene.getVariables().get("MyVar").getAsNumber()

And this one should return the string value from the global variable “MyGlobal”, and save it in “s”:

var s = runtimeScene.getGame().getVariables().get("MyGlobal").getAsString()
3 Likes

Thank you :slight_smile:

Yes I’m reading the documentation but seems like I have misunderstand the hierarchy and the API’s completely.
I never thought all of these API’s on the left does anything to each other and I can (need to) get from runtimeScene to VariableContainers’s such way :blush: