Using StoryInit to initialise data

Twine Version: 2.9.2

SugarCube 2.37.3

I want to initialise an array of dictionaries in StoryInit, but cannot access the data having done so.

I know my StoryInit passage is used because Twine catches bugs in the code there.

As a test, I have just got this in StoryInit:


<<script>>
let $test = 4
<</script>>

If I then have this in my first passage:

<<print $test>>

It reports “[undefined]”.

Anyone know what I am doing wrong?

Sugarcube doesn’t recognize the $variable markup within pure Javascript. You need to either use the State object, like this:

<<script>>
    State.variables.test = 4
<</script>>

or simply use Sugarcube syntax:

<<set $test = 4>>

Additional to @svlin advice about how use the State API to reference Story variables within JavaScript code.

The State.temporary property can be used to reference Temporary variables.

SugarCube’s engines uses a Private Scoped Context to execute JavaScript.

Things defined in one Private Scoped context are not available in another such scoped context.

The let keyword/statement is used to create JavaScript variables, not the Story or Temporary variables supported by SugarCube.

The last three points are the main reason why the JavaScript variable you created using the let keyword in the context of the <<script>> macro call was not available in the context of the <<print>> macro call, thus the “undefined” error.

Thank you. I had a feeling there was somethingf like that, but have not touched Twine in a while and could not remember.