Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

What happens if variables are not initialised? How to avoid errors.

edited February 2014 in Chit-Chat
This may well be common knowledge (I have only been using Twine a little over a week, so what do I know?), but I thought I would mention it in case it is not. What happens if you forget to initialise a variable that you are using to track state? It is going to generate an error when the player gets to a passage that uses it, right? Not if you test to see if it is defined first.

Here is an example. The variable $weapon is used to hold the player's current weapon (as an integer).

You confront the goblin with<br />&lt;&lt;if $weapon === undefined&gt;&gt;<br />your bare hands<br />&lt;&lt;elseif $weapon = 1 &gt;&gt;<br />the Sword of Fire<br />&lt;&lt;elseif $weapon = 2 &gt;&gt;<br />the Spear of Might<br />&lt;&lt;elseif &gt;&gt;<br />yours fists<br />&lt;&lt;endif&gt;&gt;<br />and it flees in terror.

The first if tests whether the variable is undefined, and if not acts accordingly. If it is defined, the rest of the code handles it based on its value.

This is great for use in a display passage.

You confront the goblin with &lt;&lt;display &quot;playerweapon&quot;&gt;&gt; and it flees in terror.<br /><br />::playerweapon<br />&lt;&lt;if $weapon === undefined&gt;&gt;<br />your bare hands<br />&lt;&lt;elseif $weapon = 1 &gt;&gt;<br />the Sword of Fire<br />&lt;&lt;elseif $weapon = 2 &gt;&gt;<br />the Spear of Might<br />&lt;&lt;elseif &gt;&gt;<br />yours fists<br />&lt;&lt;endif&gt;&gt;

Tested in Sugarcube, but this is standard Javascript, so should work in anything.

ETA: Actually, it does not work in Sugarcane (and I guess other formats) as they default all variables to zero. It is, however, useful for Sugarcube.

Comments

Sign In or Register to comment.