Wednesday, 5 March 2014

Initialising Variables

In a passage

Setting variables in a passage is easy. It is probably a good idea to have a passage dedicated to that purpose, and it might look like this:

<<set //initalising

$name = 'Boris';
$age = 43;

Note that all the work is being done inside a <<set>> macro. You can pack as much JavaScript in there as you like, and you do not need to actually set anything. What you do need is for it to start with two angle brackets, the word "set", a single space, some non-whitespace character. This will fail:

$name = 'Boris';

By the way, the double slashes, //, indicate tht what follows on that line is a comment.

In a script

Personally, I would prefer to keep my code and my text separate as far as possible. All that JavaScript should go into a script passage. Sounds easy; you might think this would work:

$name = 'Boris';
$age = 43;

It does not (probably due to scoping rules).

In Sugarcube, you have to do this: = 'Boris'; = 43;

In Sugarcane (and I guess the others):

state.history[0] = 'Boris';
state.history[0].variables.age = 43;

There is an added complication in Sugarcane that the state object  does not exist when a script passage is first run (in Sugarcube it does, so this does not apply). What you have to do then is to set the variable inside a function, and call the function. Your script will look like this;

window.myinit = function() {
  state.history[0] = 'Boris';
  state.history[0].variables.age = 43;

And you invoke it on the Start page like this:

<<set myinit() >>

No comments:

Post a Comment