Looping Constructions
We've mentioned one of the looping constructs before. Now we'll examine them more closely. RetroForth has a completely different set of loop constructs than ANS Forth, so you'll want to pay attention.
Most loops begin with the word repeat. The first kind of loop is between repeat ... until. This is a simple counted loop that exits when the TOS is zero. If it's not zero, it subtracts one from it and loops back to repeat. Try this:
: COUNTDOWN ( N -- ) repeat dup . cr until ;
16 COUNTDOWN
This word will count down from N to zero. The second type of loop RetroForth has is an unconditional loop, repeat ... again. This keeps going until you break out of it, perhaps by using ;; or pressing Ctrl-C :
: MAIN-LOOP repeat ." looping again ..." cr again ;
Consider the following word for doing character graphics. Enter:
: PLOT# ( n -- ) repeat '- emit until ;
cr 9 PLOT# 37 PLOT#
RetroForth also has a for ... next construct similar to ANS Forth. It is used like this:
: looper 10 for ." Iteration #" r . cr next ;
for ... next puts the counter on the return stack. You can use the word r to obtain this value. Like repeat ... until it counts down to zero.