The commands if, then and else provide a simple control structure.
The commands listed in Table 4-21 control the flow of conditional execution.
Table 4-21 if..else..then Commands
Command |
Stack Diagram |
Description |
---|---|---|
if |
( flag -- ) |
Execute the following code if flag is true. |
else |
( -- ) |
Execute the following code if if failed. |
then |
( -- ) |
Terminate ifelsethen. |
The format for using these commands is:
flag if (do this if true) else (do this if false) then (continue normally)
flag if (do this if true) then (continue normally)
The if command consumes a flag from the stack. If the flag is true (non-zero), the commands following the if are performed. Otherwise, the commands (if any) following the else are performed.
ok : testit ( n -- ) ] 5 > if ." good enough " ] else ." too small " ] then ] ." Done. " ; ok ok 8 testit good enough Done. ok 2 testit too small Done. ok
The ] prompt reminds you that you are part way through creating a new colon definition. It reverts to ok after you finish the definition with a semicolon.