Wednesday, 26 March 2014

The "state" variable

There is a useful JavaScript trick that will print all the properties of a variable. It might not work on all Browsers, but is good for experimenting with. In this example, it will give an alert with all the properties of the variable. This is using Sugarcube.

By the way, it is safer to do this as an alert rather than putting the result in text as the text may be part of the variable we are looking at, and you can potentially get your browser stuck in a loop.

Also, I am going to refer to these things as variables; in strict object-orientated language they are properties.

So let us start by looking at, like is:

<<set alert(JSON.stringify(>>

I set up a basic game, with this is the Start passage:

<<set $x = 4>>
<<set alert(JSON.stringify(state
<<set $y = 7>>

And I got this:


So I can see that contains the name of the current passage, and contains all the variables currently in use (in this case just $x had been set).

We can take that back a step and look at state. I am going to add a link to a second passage, that links to a third passage, which links back here, and the second page also sets $z to 10:

<<set $x = 4>><<print JSON.stringify(state)>>
<<set $y = 7>>

Now we see this:


So we can see that holds the current values, while state.history contains an array of historic values of each page visited in order.

Let us see what Sugarcane does.:

{"history":[{"passage":{"title":"Start","id":2,"tags":[],"text":"A first page.\n\n<<set $x = 4>>\n<<set alert(JSON.stringify(state))>>\n<<set $y = 7>>\n[[Two]]"},"variables":{"x":4,"y":7,"z":10}},{"passage":{"title":"Three","id":0,"tags":[],"text":"[[Start]]"},"variables":{"x":4,"y":7,"z":10}},{"passage":{"title":"Two","id":1,"tags":[],"text":"A second page.\n<<set $z = 10>>\n[[Three]]"},"variables":{"x":4,"y":7,"z":10}},{"passage":{"title":"Start","id":2,"tags":[],"text":"A first page.\n\n<<set $x = 4>>\n<<set alert(JSON.stringify(state))>>\n<<set $y = 7>>\n[[Two]]"},"variables":{"x":4,"y":7}},{"passage":null,"variables":{}}],"id":"1395737963066"}

Sugarcane is rather different. It has no active variable. Its history variable holds an array just like Sugarcube, but in reverse order, so for Sugarcane, state.history[0] is always the current page, for Sugarcube it is the first page.

Sugarcane also has a passage variable, and the passage title is in there, as well as the tags and the whole passage text. As you can see this means a lot more data being stored.

No comments:

Post a Comment