-
Notifications
You must be signed in to change notification settings - Fork 0
05. Block Elements
When the interpreter encounters an opening brace {, it switches from execution mode to collection mode. While in collection mode, tokens will simply be accumulated rather than executed. The interpreter will return to execution mode once the closing brace } paired with the original opening brace is read, at which point a block element containing all tokens enclosed within the braces will be added to the stack.
Like any other element, block elements can be stored in a variable. They can also be used to define auto-executing macros. For example, the isEven macro below will pop an integer value and push a true or false boolean value:
# int -> bool
/isEven {
1 & 0 ==
} macro
Block elements are also used in control flow statements. The following program prints whether integers up to ten are even by using the loop, if and ifelse keywords:
/n 0 def
{
/n ++ # Increment n
n 10 > { break } if # Break out of loop if n > 10
n " is " ~ # Concatenate n with " is "
n isEven { "even" } { "odd" } ifelse ~ # Concatenate previous string with "even" or "odd"
println # Print string
} loop
The keyword break causes the interpreter to end the current loop. The other related keywords are continue, which moves to the next loop iteration, and quit, which stops the entire program.