IfElse
Description: |
Returns the result of one of two expressions depending upon the result of a conditional expression. |
Returns: | Varies |
Usage: | Script or steady state. |
Function Groups: | Logic Control |
Related to: | Ternary Operator (IfElse) | Cond | Execute | IfThen |
Format: |
IfElse(Condition, TRUECase, FALSECase) or Condition ? TRUECase : FALSECase |
Parameters: |
Condition |
Required. An expression that returns true or false. If true the TRUECase is executed. If false, the FALSECase is executed. If invalid, neither case is executed. |
TRUECase |
Required. The expression (typically an Execute statement) which is executed when Condition is true. |
FALSECase |
Required. The expression (typically an Execute statement) which is executed when the Condition is false. |
Comments: |
This is simply a different name for the Cond function. The return value is the result of the evaluated case. Both cases are evaluated, in which case Cond is a more apt name. Writing long "If Else - Else - Else ... " expressions is not efficient and can be avoided in many situations. A common task is to build a string based on the current value of one or more other tags. For this example, suppose that you need to build a message that varies by some situational ID and a matching state. The message will be a combination of a prefix that indicates the situation and a suffix that indicates the state. Monitoring the situation, you have tags [Situation ID] and [Current State]. A long and inefficient method might be to write: [Situation ID] == 1 ? Concat("Prefix A ", Instead of this, do the following: 1. Create a set of application properties for each situational prefix and state suffix: Situation1 = Prefix A: Situation2 = Prefix B: Situation3 = Prefix C: State1 = [Suffix A] State2 = [Suffix B] (etc.) 2. Write an expression that concatenates the appropriate properties into a message based on the value of your two tags: Concat( Variable(Concat("Situation", [Situation ID])), Variable(Concat("State", [Current State])) ) No comparisons or If-Else statements are required. Those four lines of code can create as many combinations of situation prefixes and state suffixes as you need. |
Scripting example:
If 1 Main; [ IfElse(i > 0 && i <= 50, Execute(y[i] = x, i++), { else } Execute(x = i, doneFlag = 1) ); ]
This statement will set the element of array y equal to i and then increment i if i is between 1 and 50 inclusive. If i is not in that range, x will be set to i and doneFlag will go true. Note that Execute may only appear in a script.