Sunday 2 March 2014

Handling variables that have not been initialised

What happens if you forget to initialise a variable that you are using to track state? If you are using Sugarcube, 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
<<if $weapon === undefined>>
your bare hands
<<elseif $weapon = 1 >>
the Sword of Fire
<<elseif $weapon = 2 >>
the Spear of Might
<<elseif >>
yours fists
<<endif>>
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 <<display "playerweapon">> and it flees in terror.

::playerweapon
<<if $weapon === undefined>>
your bare hands
<<elseif $weapon = 1 >>
the Sword of Fire
<<elseif $weapon = 2 >>
the Spear of Might
<<elseif >>
yours fists
<<endif>>


In other formats (Sugarcane, etc.) variables default to zero, so this is not relevant.

4 comments:

  1. Excellent example on how to test if a variable has been initialized.

    I don't know if you are aware but SugarCube supports a special passage named StoryInit, which is where the creator suggests you place your variable initialization.

    ReplyDelete
  2. I came across this looking on how to check for undefined variables in Sugarcube 2 after further searching it is
    <>

    ReplyDelete
  3. Sorry for the spam, correct way to check for undefined in Sugarcube is << if ndef $myvar >>

    ReplyDelete