The commands if, else and then provide a simple control structure.
The commands listed in Table 4-28 control the flow of conditional execution.
Table 4-28 ifelsethen Commands
Command |
Stack Diagram |
Description |
---|---|---|
if |
( flag -- ) |
Execute the following code when flag is true. |
else |
( -- ) |
Execute the following code when flag is false. |
then |
( -- ) |
Terminate ifelsethen. |
The format for using these commands is:
flag if (do this if true) then (continue normally)
flag if (do this if true) else (do this if false) then (continue normally)
The if command consumes a flag from the stack. If the flag is true (nonzero), 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.