Scripting tutorial #7: Making Decisions

The power of 'if'

One of the most useful things about programming is that you can automate complex tasks. However, these programs need to be able to respond to various situations that might arise. What should a thermometer program do if the outside air is below freezing? How should a program respond when a file is missing? And what happens when a cat wanders across the keyboard while the user is typing something in?

To solve this problem, programming languages offer different ways to change which instructions are followed next. In the case of our scripting language, this is done through the JUMP, JUMPIF, and LABEL commands. While this isn't as clean as the if ... then statements of higher level languages, it's fairly similar to the methods assembly languages have used for decades.

Moving around

The JUMP, JUMPIF, and LABEL commands work together to create branching paths in your code. JUMP tells the scripting engine to move to the LABEL with the same name, while the JUMPIF command only changes paths if the .RESULT variable is not zero. The only restrictions to these commands' abilities is that the JUMP/JUMPIF commands must be referencing a LABEL in the same function.

As a general rule, it's a good practice to write your scripts so that your JUMPs are always referencing a LABEL further down the page. In other words, try to write your JUMPs so they are used to skip over code. Using JUMPs to go backwards is possible, but it should only be done to repeat instructions, not control the program's flow. See spaghetti code for some insights into this problem.

Making decisions

Most of the time, JUMP/JUMPIF commands are going to be used to change the script's behavior based on a comparison. Each of the examples at the top of this page involved a comparison of some sort: you'd need to check if a temperature was below zero, if a file exists, and if the input from the user was valid.

So, there are a handful of commands that let you compare things. The include EQUAL, GTHAN, and LTHAN. Each of these commands take two parameters, and sets .RESULT to 0 or 1 based on what they find. This allows them to be paired with JUMPIF, and in turn, this lets the script make simple decisions.

Here's an example to illustrate this:

START
EQUAL 1 2
JUMPIF AreEqual
ALERT "1 is not equal to 2"
JUMP Exit

LABEL AreEqual
ALERT "1 is equal to 2, somehow"

LABEL Exit
END

When run, this example should display a message saying that the numbers 1 and 2 are not, in fact, equal. This is something most of us already know to be true, but alas, computers need to figure this out on their own.

 

You're almost done with this tutorial - just two more pages to go!

 

Onwards! -->

<-- Back to the previous tutorial page

Project Hosted by
Download Mike\'s Sprite Editor