Page 136 - The Unofficial Guide to Lego Mindstorms Robots
P. 136
125
Conditionals and Loops
Forth supports a standard IF statement, though the order is switched around from what you might be used to. The IF word
comes in two different varietie s:
condition IF body THEN
T he IF word looks at th e condition on the stack . If the condition is true, the body between IF and THEN is executed.
Table 6-3 lists some of the mathematical condition words t hat are available.
Table 6-3. Mathem atical Condition Words
Word Description
< Compares the top two items on the stack; replaces them with true if the second item is less than the top item, false otherwise
= Compares the top two items on the stack; replaces th em with true if they are equal, false otherwise
> Compares the top two items on th e stack; replaces them with true if the second item is greater than the top item, false
otherwise
0< Replaces the top item of the stack with true if it is less than zero; false otherwise
0= Replaces the top item of the stac k with true if it is equal to zero; false otherwise
Th e following example prints out a message if the top item on the stack is less than 0:
: negative 0< IF ." less than zero " THEN ;
ok
-2 negative
less than zero ok
2 negative
ok
The 0< word examines the top value on the stack. The result of this comparison is examined by the IF word. If it is true, the
body of the IF is executed. The .“ word tells pbFO RTH to print text to the console, up until the ” word. Finally, THEN
marks the end o f the body of the IF.
There's also a s lightly more complicated IF word:
condition IF trueBody ELS E falseBody THEN
T his is the same as bef ore, except words between ELSE and THEN will be executed if the condition is false.
Forth also includes some simple loops, including:
limit start DO words LOOP
This loop performs the given words limit - start times. Internally, a loop index is given the value start. Each time
through the loop, the index is increased by one. When it is equal to limit, the loop ends. You can put the