Loop Control

if

The if statement in stack-based programming works as follows:

expression or boolean value
[quoted instruction to execute if condition true]
[quoted instruction to execute if condition false]
if

This statement pops two quoted instructions and a boolean value or expression from the stack. If the value is true, it executes the first instruction. Otherwise, it executes the second instruction.

Example:

Suppose we have the following instructions on the stack:

true [5 6 *] [3 2 *] if

After executing this if statement, the result will be:

30

Because true is on the stack, it executes the second quoted instruction in the stack [5 6 *], which multiplies 5 and 6, resulting in 30.

If the boolean value is false, it executes the first quoted instruction.

You can also use the if instruction in this way:

[quoted instruction to execute if condition true]
[quoted instruction to execute if condition false]
if(instruction)

where first the two quoted instruction are popped, then instruction will be executed, then a value will be popped and that will be our boolean for the branch

Example:

-2 [5 6 *] [3 2 *] if( 2 + 0 ==) => 30

nop

The nop operation simply does nothing. It can be useful as a placeholder or for alignment purposes.

Example:

Suppose we have the following instructions on the stack:

empty [nop] [ 6 *] if

After executing this if statement, the program will do nothing.

Assuming the stack was empty before executing the code, false will be on the top of the stack, so if will execute the second quoted instruction [nop] preventing the program from a stack underflow.

The nop operation has no effect on the stack.

Example:

Suppose we have the following instructions on the stack:

5 3 + nop

After executing the nop operation, the stack remains unchanged:

8

loop

The loop operation execute the first instruction on the stack, then it will pop a value that must be boolean, and if it is true it will execute the instruction again, if it is false the loop stops. You can think of it as a while-do loop

Example:

1 [1 + dup 10 <] loop => 10

The loop can be perform also with [instructions] loop(condition) but in this way it executes the condition expression first. You can think of it as a while loop

Example:

0 [0 swap] loop(1 + dup 3 <) => 0 0 3

0 [0 swap 1 + dup 3 <] loop => 0 0 0 3