How to evaluate sugarcube variables format in a javascript function?

Story Format: SugarCube v2.29


So I have a javascript function that take a string as argument. That string can be a simple string OR a sugarcube variable format “$variables”. In this second case I would like to get the real value of the variables.

function getRealValueIfVariable(str) {
   return magicFunction(str);

/* For example if I have $name set to "John" I would like the function to return */
==> "name"
==> "John"

Do you know a way to do it ?

Thanks in advance guys have a good day!

You can use the State.getVar() function to access the current value of a Story Variable using the TwineScript format of its name.

1 Like

A better way to access the variables would simply be by using the State.variables object for story variables and the State.temporary object for temporary variables.

Using those objects, you have no need for such a function. If you want to access $name in JavaScript, then you’d just use instead. If the name of a variable is in another variable, then you can do this:

var variableName = "name";
var result = State.variables[variableName];

This also allows you to set variables from JavaScript:

// Make sure the first letter of the name is capitalized. =;

If you need to work with a lot of variables and don’t want to type “State.variables” over and over, you can shorten that like this:

var sv = State.variables;
// Make sure the first letter of the name is capitalized. =;

Hope that helps! :slight_smile:

1 Like