Loops
Loops may be created using the Forth words do and loop. The following simple example prints out five new lines:
5 0 do cr loop
This is equivalent to the following for loop in C:
for (i = 0; i < 5; i++)
{
printf("\n");
}Tip
Note that in some Forths, the loop constructs described in this section may be used only inside word definitions. Gnu's gforth is an example of such a Forth. In other Forths, you can quite happily use them from the command line. It all depends on which implementation you are using.
Now in C, you're not limited to incrementing the loop counter by 1. Forth doesn't have this limitation either. Instead of using loop, the word +loop takes a value from the stack and uses it to increment the loop count. Here is an example where the loop is incremented by 2 each iteration:
10 0 do cr 2 +loop
This is very versatile. In the previous example, the value by which the loop was incremented was specified just prior to +loop. However, since +loop takes a value from the stack, that value could just as easily be unspecified until runtime, and it could also be varied for each iteration of the loop simply by modifying that stack entry.
do (destructively) takes two operands off the stack and uses these for the loop count. In the previous examples, the loop executes the word cr five times. The operands can just as easily be supplied by other Forth words. In this example, the loop executes twice:
100 98 - 0 do cr loop
Alternatively, a word definition using do ... loop may take one ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access