Last updated: 22 May 21 00:16:43 (UTC)
How do I pass variables between Twine and javascript? - IF Answers
Short version:
For variables “tvar" as the twine variable, and “jvar" as the JS variable:
- JS to Twine:
- Within JS, use “State.variables.tvar = jvar;"
- Or
<> prerender.foo = function(x) { state.active.variables[“tvar"]=“quux”; } <>
- Twine to JS:
- In JS, use “var jvar = state.variables.tvar;"
How do I pass variables between Twine and javascript?
askedApr 13 in Authoringbypeterorme(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.
1 Answer
answeredApr 13 bypeterorme(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.
This site is now closed.
As of 1st November 2015, this site is a read-only archive. For more information see the intfiction forum post
Welcome to IF Answers, a site for questions and answers about Interactive Fiction.
Technical questions about interactive fiction development tools such as Inform, Twine, Quest, QuestKit, Squiffy, Adrift, TADS etc. are all on-topic here.
Non-technical questions about interactive fiction are also on-topic. These questions could be about general IF design, specific games, entering the IF Comp etc.