205a
<< <> >>

205

The programming language Forth
home

Control structures II

4. WHILE

WHILE is the solution we hinted at last time. This is an IF that swaps its administration packet with the administration packet of the enclosing structure. That's why WHILE can only be used inside other control structures. The other structures should have been closed before the accompanying THEN follows. WHILE nests crosswise, and serves to jump out of a structure, to THEN:
: WHILE ( -- )
  POSTPONE IF
  1 CS-ROLL ; IMMEDIATE

 .. BEGIN .. WHILE .. AGAIN  THEN ..
      1        2        1      2
The numbers indicate how the words are linked. WHILE can be used inside all other control structures. Examples:
a) .. BEGIN .. WHILE .. UNTIL .. THEN ..
        1        2        1        2

b) .. BEGIN .. WHILE .. AGAIN  ELSE .. THEN ..
        1        2        1      2       2

c) .. BEGIN .. WHILE .. WHILE .. AGAIN  THEN .. THEN ...
        1        2        3        1      3       2
In c) WHILE-2 shoves its compiler administration under BEGIN-1, WHILE-3 shoves its compiler administration also under BEGIN-1, where it lands on top of WHILE-2. Internally, both WHILE's are nested normally.

Trick question:
What's the difference between OIL and VINEGAR ?
: OIL     aaa IF bbb IF ccc THEN THEN ddd ;
: VINEGAR aaa IF bbb WHILE ccc THEN THEN ddd ;
Remark:
REPEAT (a standard word) is actually the same as AGAIN THEN.
.. BEGIN .. WHILE .. REPEAT ..
>>