Page 77 - The Unofficial Guide to Lego Mindstorms Robots
P. 77
66
Loops
A loop is a series of commands that you want to be executed repeatedly. NQC offers three flavors of loop:
repeat (expression value) [statements]
Th is command simply repeats the given statements value times.
while (boolean condition ) [statements]
This loop repeats the supplied statem ents until condition is no longer true.
do [statements] while (boolean condition)
This loop is similar to while bu t the statements are executed before the condition is tested. The statements will always
be executed at least once, wh ich is not true for a while loop.
Let 's look at an example. The following code plays a sound every half second while a light sensor attached to input 3 sees dark:
while (SENSOR_3 < 35) {
PlaySound(0);
Wait (50);
}
No tice how curl y braces are used to bracket the statements that belong to the while loop. If you have only one command in
th e body of the while , you can omit the braces like this:
while (SENSOR_3 < 35)
Wait(50);
Conditionals
To test a condition, use the if command.
if (boolean condition) [statements]
T his command executes the given statemen ts only if condition is true.
if (boolean condit ion) [statements] else [statements]
This is a simple variation on the basic if comm and. If the condition is false, the statements after the else are executed.
Th e following exampl e turns different directions depending on the value of input 2:
SetPower(OUT_A + OUT_C, OU T_FULL);
if (SENSOR_2 < 50) {
Fwd(OUT_A);
Rev(OUT_C);
}
else {
Rev(OUT_A);
Fwd(OUT_C);
}
On (OUT_A + OUT_C);