All Smurf commands are executed unconditionally, so the only way to accomplish conditional execution is by using the ‘x’ command to execute a new program. The Smurf programming language specification describes the ‘x’ command as follows:
x - Executes the string on top of the stack as a Smurf program. The stack
and variable store are cleared before it is executed.
It should be noted that once the command is used, the program that called it effectively ceases to exist, and there is no way to return control to the calling program.
This document explains basic conditional execution in Smurf (equivalent of the ‘if’ command of other languages); looping is described in the document Looping In Smurf (coming soon).
The simplest form of conditional execution executes different code based on a number of specified possibilities. The following non-interactive program outputs ‘Hello world’ if the input is ‘gb’, ‘Hey world’ if the input is ‘us’, and ‘G’day world’ if the input is ‘au’:
1 "Hello world""gb"p
2 "Hey world""us"p
3 "G'day world""au"p
4 ig
5 q"o"+x
The input is used as the name of a variable. As all Smurf variables are initialised to the empty string, the program gives no output if the input was invalid. This is clearly a contrived example, as a direct mapping of input to output can be done without the 'x' command, but examples of this form better illustrate the concepts than very long Smurf programs that actually process data.
The following interactive program outputs ‘You were quick’ if the user gave input before the ‘i’ command is encountered, and ‘You were slow’ otherwise:
1 "?"""p
2 ig
3 "You were slow""?"p
4 "You were quick"""p
5 g
6 q"o"+x
This program uses a two-stage process to check if the input was the empty string (often called 'null'). Lines 1 and 2 map the empty string onto ? (which could be replaced throughout the program by any other non-null string), and any other input onto the empty string. Lines 3 to 5 map ? onto the appropriate string for null input, and the empty string onto the appropriate string for non-null input.
The examples above do not store the input for later use in the program. The following non-interactive program tells the user whether they gave input to the program, and what that input was:
1 "?"i+""p
2 ""gtg
3 "You entered no input""?"p
4 "Your input was """gt+""p
5 g
6 q"o"+x
Lines 1 and 2 map the empty string onto ?, and any other input onto the empty string.
If, however, the input is not the empty string, the the variable whose name is the empty string consists of the input with an additional ? prefixed.
The value can the be retrieved and used later in the program, as the commands ""gt demonstrate on line 4.