If-then-else
The if-then-else statement evaluates a boolean (true/false) expression. If the expression yields true, the statement block following then is executed. Else, if the expression is false, execution goes to the else statement block, if present. Execution the continues normally after the end statement.
The syntax is as follows, with the
else clause being optional:
if <condition> then
<statements>
[else
<statements>]
end
The following example is used with
display and
input statements to capture end user feedback. This particular example evaluates the variable
selected and sets the predefined
action variable to FAIL:
if selected = "Cancel" then
action = FAIL
end
The following example evaluates the variable
orderTotal. If the order is greater than $5,000, the Boolean variable
checkCredit is set to
true:
if orderTotal > 5000 then
checkCredit = true
end
We can go one step further with the previous example. We can also check whether the order is a credit order or a cash order by using the logical operator
and to verify the two conditions. As before, the code checks if
orderTotal is greater than $5,000 and now also requires that
paymentType be set to "Credit":
if orderTotal > 5000 and paymentType = "Credit" then
checkCredit = true
end
The final example shows the use of the
or
logical operator and the
else clause. This example checks whether the variable
lollipop is "cherry" or "raspberry". If so,
eat is set to
true. If not,
eat is set to
false:
if lollipop = "cherry" or lollipop = "raspberry" then
eat = true
else
eat = false
end
Elseif
Some times you will need to handle more than two alternatives. To support this situation you can use the optional
elseif clause:
if <condition> then
<statements>
[elseif <condition> then
<statements>]
...
[elseif <condition> then
<statements>]
[else <condition> then
<statements>]
end
In effect, each
elseif concatenates two
if-then-else statements. An arbitrary number of
elseif blocks can be included, as well as a single optional
else clause at the end. The example below uses the
elseif clause and the
else clause. This way, you can continue adding conditions indefinitely:
if selected = "Cancel" then
action = FAIL
elseif selected = "Process" then
orderStatus = "Reviewed"
financeStatus = "Check"
else
orderStatus = "In Review"
end
For situations where program flow must follow several possible options based on only one parameter, it is better to use the case statement.