Login
Remember
IF Answers
Ask a Question

# How do I pass variables between Twine and javascript?

+1 vote
318 views
asked Apr 13 in Authoring by peterorme (104 points)
edited Apr 13 by peterorme

How do I pass variables between Twine and javascript? Is this different for different versions of Twine and/or different story formats?

In Twine 1.4 using the Sugarcane story format, Twine variables are in `state.history[0].variables` javascript variable, but with SugarCube I guess they are somewhere else.

- twine
- sugarcube

## 1 Answer

+1 vote
answered Apr 13 by peterorme (104 points)
selected Apr 20 by peterorme
Best answer

I found the answer in the sugarcube Story API.

With Sugarcube, you need to use `state.active.variables` rather than `state.history[0].variables`.

For example (using Twine 1.4 with a Sugarcube 1.0.19 story format), you can add a passage with the script tag and do this

    prerender.foo = function(x) {
      state.active.variables["bar"]="quux";
    }

And in a passage you can do

    bar is <<print $bar>>

The prerender function (arbitrarily named "foo") will be run before any passage, and set the "bar" variable to "quux". In the passage you can access this as $bar.

To do the reverse (use a Twine variable in JavaScript code), just do the reverse:

in a passage, do

    <<set $bar = "quux">>

and in javascript:

    var bar = state.active.variables.bar;

To do the same thing in the built-in story formats (Sugarcane, Jonah, Responsive) you just need to use state.history[0] instead of state.active.

## Related questions

- Twine with sugarcube: can you display visited links differently?
- How can I add changing maps or inventories to a Twine game?
- Twine: how can I check if a passage has been visited?
- In Quest, how do I send an integer from javascript to Quest and keep it an integer?
- How can I find a good Twine game?

...