If conditional control
The IF instruction allows you to decide whether to execute a code block. The decision comes from the control of a relational expression, that is an expression that always returns a Boolean result TRUE or FALSE. The syntax is as follows:
- If (RelationalExpression)
- Instruction1...
- Instruction2...
- EndIf
Relational Expression represents the relationship between operands from which a Boolean result is returned. If the result is TRUE, the code block between If and EndIf is executed. The keyword "EndIf" always closes the code block opened by If. If the expression returns FALSE, execution skips to the following "EndIf" instructions.
For example:
- x = 10
- If x > 5
- Circle(50,50,30)
- EndIf
We instantiated a variable named "x". The If block is executed only if "x" is greater than 5. Since the variable contains 10, a circle is drawn.
An if instruction can be accompanied by an ELSE instruction. ELSE allows both states of the initial Boolean expression to be used, because it delimits the block of code executed if the condition is FALSE.
- If (RelationalExpression)
- Instruction1...
- Instruction2...
- Else
- Instruction3...
- Instruction4...
- EndIf
If the expression returns the TRUE value, the IF block consisting of instruction 1 and 2 is executed, otherwise the interpreter executes the code block consisting of instruction 3 and 4.
For example:
- x = 10
- If x > 5
- Circle(50,50,30)
- Else
- Square(20,20,30)
- EndIf
In this example, if the variable "x" is greater than 5 a circle is drawn, if it is less than or equal to 5 a square is drawn (the instruction contained in the ELSE block).
Within an IF or IF ELSE instruction, another IF instruction can be contained. In this particular case we are in the presence of nested IF.
- If (RelationalExpression)
- Instruction1...
- Instruction2...
- If (RelationalExpression)
- Instruction5...
- EndIf
- Else
- Instruction3...
- Instruction4...
- EndIf
The IF conditions can be used in chain using the ELSEIF special instruction. In this particular type of concatenation several relational expressions are evaluated proceeding in chain, from top to bottom. If one of the conditions is TRUE then the corresponding code block is executed. Otherwise, if present, the final ELSE code block is executed.
- If (RelationalExpression1)
- Instruction1...
- Instruction2...
- ElseIf (RelationalExpression2)
- Instruction3...
- Instruction4...
- ElseIf (RelationalExpression)
- Instruction5...
- Instruction6...
- Else
- Instruction7...
- Instruction8...
- EndIf
If expression1 is TRUE, instruction block 1 and 2 are executed, otherwise, if expression2 is TRUE, instruction blocks 3 and 4 are executed, otherwise, if expression3 is TRUE, instruction blocks 5 and 6 are executed, otherwise, the final Else code block consisting of instructions 7 and 8.