IF … THEN … ELSEIF … ELSE … ENDIF
- Last UpdatedSep 14, 2023
- 2 minute read
IF-THEN-ELSE-ENDIF conditionally executes various instructions based on the state of an expression. The syntax is as follows:
IF <Boolean_expression> THEN
[statements];
[ { ELSEIF
[statements] } ];
[ ELSE
[statements] ];
ENDIF;
Where Boolean_expression is an expression that can be evaluated as a Boolean.
Depending on the data type returned by the expression, the expression is evaluated to constitute a True or False state according to the following table:
|
Data Type |
Mapping |
|---|---|
|
Boolean, Discrete |
Directly used (no mapping needed). |
|
Integer |
Value = 0 evaluated as False. |
|
Float, Real |
Value = 0 evaluated as False. |
|
Double |
Value = 0 evaluated as False. |
|
String, Message |
Cannot be mapped. Using an expression that results in a string type as the Boolean_expression results in a script validation error. |
|
Time |
Cannot be mapped. Using an expression that results in a time type as the Boolean_expression results in a script validation error. |
|
ElapsedTime |
Cannot be mapped. Using an expression that results in an elapsed time type as the Boolean_expression results in a script validation error. |
|
Object |
Using an expression that results in an object type. Validates, but at run time, the object is converted to a Boolean. If the type cannot be converted to a Boolean, a run-time exception is raised. |
The first block of statements is executed if Boolean_expression evaluates to True. Optionally, a second block of statements can be defined after the keyword ELSE. This block is executed if the Boolean_expression evaluates to False.
To help decide between multiple alternatives, an optional ELSEIF clause can be used as often as needed. The ELSEIF clause mimics switch statements offered by other programming languages. For example:
IF value == 0 Then
Message = "Value is zero";
ELSEIF value > 0 Then
Message = "Value is positive";
ELSEIF value < 0 Then
Message = "Value is negative";
ELSE
{Default. Should never occur in this example};
ENDIF;
The following approach nests a second IF compound statement within a previous one and requires an additional ENDIF:
IF (X1 == 1) THEN
X1 = 5;
{ ELSEIF <X1 == 2> THEN
X1 = 10;
ELSEIF X1 == 3 THEN
X1 = 20 ;
ELSEIF X1 == 4 THEN
X1 = 30 };
IF X1 == 99 THEN
X1 = 0;
ENDIF;
ENDIF;
See Sample Scripts for more ideas about using this type of control structure.