Tutorial Details:
Difficulty Level:
Intermediate
Topics Covered: Using
the Select statement to make decisions.
Assumed Knowledge:
The Basics, My First Program, Constants and Variables,
Conditionals (if)
Written By: BILL LANE
BACK
As we discussed in Conditional (If) it is very important
to have a method to make decisions once our program is running.
There is an excellent alternative to the if
statement in the form of the select
statement. Select is ideal
when there are a number of possible options and is a lot neater
than using nested if statements
(that is if's inside if's inside if's). But it only works
when you know exactly what the values will be. You can't use
select to check if a value
is greater than, or less than another value. So let's consider
a situation where you would use select.
Let's imagine you are building a mission that has a number
of distinct stages. There may be a setup stage, a normal running
stage, a I've been hit stage, a mission successful stage and
a time up stage. You would typically assign a number to represent
these different stages and have a variable to keep track of
the current value. You could then use a select
statement in your code to determine the current game state
and respond in an appropriate manner. Let's see how this might
work:
select gGameState{
when 1 {sound 1}
when 2 {sound 2}
when 3 {sound 3}
else {sound 4}
}
In this example, we start with the select
keyword and then we have the name of the value we want to
check. I'm checking on a global variable (hence the g at the
start) gGameState. This is followed by an opening curly brace,
with the closing curly brace encompassing a series of when
statements.
The when statements are
simple enough. The first when
statement basically says that if gGameState equals 1 then
play sound 1. The code checks each line and if it finds a
match it executes the commands inside the curly braces. I've
just used one command, but there can be multiple commands
spanning many lines for each option. Note the else
keyword after the last when.
This works exactly the same as with the if
statement and may be omitted if not required. If you don't
include an else and none of the whens match then the program
will continue on.
The select statement is very straight forward. But it's also
incredibly useful. So keep it in mind when you need to make
an important decision.
|