As mentioned by @fxshrat in ValueWhen - how to use a typical mistake users make is that they mix up if
statement with IIf()
function.
IIf()
(which stands for "immediate if") is a function, which means it takes arguments and returns the result
result = IIf( condition, YesValue, NoValue );
It works with both numbers (scalars) and arrays. When any of arguments is an array it returns array. It goes bar by bar, checks condition
again bar by bar and returns either corresponding array value from YesValue
or NoValue
arrays depending if condition
at given bar is true or not.
Note that IIf()
function does NOT change the flow of the program. It evaluates ALL arguments, both yesValue
and noValue
.
On the other hand if / if-else
is a flow-control statement. It is used to change the flow of the program. It decides whenever take this or that path in the program. It decides once and requires scalar value (either true (non-zero) or false (zero)) to decide.
You can not use if / if-else
on arrays directly because arrays have many values - different value in each array element.
The only way to use if / if-else
statements on arrays is to pick up array element you want to use for flow control, for example:
if( array[ BarCount - 1 ] > 0 )
{
// do something else when last element of array
// is greater than zero
}
An interesting example is showing what IIf()
function does by re-implementing it using if-else
statement.
In the code below we are using for loop to go thru all bars and if-else
statement checks individual array elements one by one to decide which path to take.
function ImmediateIf( conditionArray, yesValueArray, noValueArray )
{
for( bar = 0; bar < BarCount; bar++ )
{
if( conditionArray[ bar ] )
result[ bar ] = yesValueArray[ bar ];
else
result[ bar ] = noValueArray[ bar ];
}
return result;
}