Page 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 varieties:
condition IF body THEN
The IF word looks at the 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 that are
available.
Table 6-3. Mathematical 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 them with true if they are equal, false otherwise
>
Compares the top two items on the 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 stack with true if it is equal to zero; false otherwise
The 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 pbFORTH to print text
to the console, up until the ā word. Finally, THEN marks the end of the body of the IF.
There's also a slightly more complicated IF word:
condition IF trueBody ELSE falseBody THEN
This is the same as before, 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