Tutorial Details:
Difficulty Level:
Intermediate
Topics Covered: Using
loops in Mindscript.
Assumed Knowledge:
The Basics, My First Program
Written By: BILL LANE
Print Version
In our continuing series on common programming structures
this tutorial is all about looping. Running a loop allows
us to run through a series of commands for a fixed number
of times or indefinitely. There are a couple of reasons why
we might want to do this. For a start if we want to run a
sequence of commands more than once we might want to use a
repeat. Let's look at
an example:
repeat 5{wait 50 sound 1}
This code runs the commands inside the braces 5 times and
then ends. The result is five beeps in quick succession. We
could make our Spybots behaviour a little less predicatable
by introducing a random
element to the equation:
repeat random 1 to 5{wait 50 sound 1}
In this example the commands will repeat between 1 and 5
times before ending.
Sometimes we want a series of commands to execute indefinitely.
For example we might use a select statement to continuously
check a variable and redirect our Spybot's actions when a
change occurs:
forever{
select myVariable{
when 1{sound 1}
when 2{sound 2}
when 3{sound 3}
}
}
Yet another loopy option is to use while.
When we use while the
commands continue to run as long as a condition is true. Here
are a few different examples:
while myVariable = 3{wait 50 sound 1}
while myVariable is not 3{wait 50 sound 1}
while myVariable is 1..4{wait 50 sound 1}
The first example shows a typical conditional argument using
equals. But it could also be replaced with > (greater than),
< (less than) or <> (not equal). The second example
demonstrates an alternative form of not equal. While the last
example provides a range (1 to 4).
Well that just about covers it. We've looked at using
repeat to repeat a series of commands a fixed number
of time. We've used forever
to loop indefinitely and we've used
while to loop until a condition is false.
|