Looping and structured programming

The control words available for structured programming are shown in Table2, where xxx and yyy denote sequences of words and cond denotes a boolean flag value. Within the body of a for loop, you may get the loop counter with the word r@. It counts from u-1 down to 0. If you exit from a for loop, you must drop the loop count with rdrop.


Table 2: Flow control in FlashForth.
Code Description
cond if xxx else yyy then Conditional execution.
begin xxx again Infinite loop.
begin xxx cond until Loop until cond is true.

begin xxx cond while yyy repeat Loop while cond is true, yyy is not executed on the last iteration.

u for xxx next Loop u times.

leave Sets loop counter to zero so that we leave the loop when next is encountered.

exit Exit from a word.



Here are a couple of examples of counted loops, one constructed from the generic begin...until construct, and the other using the dedicated for...next construct. Note the difference in counter ranges.

-countdown  ok<#,ram>
marker -countdown  ok<#,ram>
: countdown1 ( n --) 
  begin cr dup . 1- dup 0= until 
  drop ;  ok<#,ram>
5 countdown1 
5 
4 
3 
2 
1  ok<#,ram>
: countdown2 ( n --) 
  for cr r@ . next ;  ok<#,ram>
5 countdown2 
4 
3 
2 
1 
0  ok<#,ram>
It was convenient, when setting up these examples, to put the source code into a little file that could be reloaded easily each time the source text was changed.
-countdown
marker -countdown
: countdown1 ( n --)
  begin cr dup . 1- dup 0= until
  drop ;
5 countdown1
: countdown2 ( n --)
  for cr r@ . next ;
5 countdown2


Peter Jacobs 2013-06-12