Extra Control Structures

In addition to all the standard ANS Forth control structures, CamelForth also provides two additional ones, detailed below.


?IF

?IF works in exactly the same way as IF, except that it is non-destructive; ie it leaves the conditional value on the stack rather than consuming it. This is often quite useful and avoids a DUP IF.


FOR...STEP

This looping structure (actually the same as FOR...NEXT used in some of Chuck Moore's Forths) takes a single unsigned index and runs through the loop decrementing it until it reaches zero. The current value of the index can be retrieved from the top of the return stack if desired (do not use I or J!).

Using this structure is almost always much more efficient than DO...LOOP, and can be used in fast code whereas DO...LOOP cannot.

This example emits 10 asterisks:

    : DEMO  10 FOR  42 EMIT  STEP ;
    DEMO

You can simulate a ?FOR-type structure efficiently like this:

    : STARS ( n -- )  ?DUP IF  FOR  42 EMIT  STEP  THEN ;
    5 STARS CR  0 STARS CR  1 STARS CR


More about CamelForth

Back to the Z88 home page