-1

I am trying to find a more concise way to compare a variable to a range of numbers.

Currently I do: IF int_variable=67 or int_variable=68 or int_variable=69 then...

Is there a way to write something like: IF int_variable=67 through 69 then

Thanks in advance.

4 Answers4

1

If you really mean that if the variable is in range of those numbers, it's just simple as this. But in more complex situations you have no shortcuts, just use Jakobs method or similar.

IF int_variable >= 67 AND int_variable <= 69 THEN
    //It is 67, 68, or 69
END_IF
Quirzo
  • 1,183
  • 8
  • 10
0

You could for example use a for-loop, like:

FOR nCounter := 67 to 69 by 1 DO
    IF int_variable = nCounter THEN
        ....
        EXIT; // If you want to exit the loop
    END_IF
END_FOR
Jakob
  • 1,288
  • 7
  • 13
  • Thanks Jakob. It will of course depend how large of a range being compared, but this feels as complex as comparing them individually. I was hoping for something like int_variable=67..69 or int_variable=67,68,69 that I had missed in the ST documentation. – controlmouse May 17 '19 at 19:03
0

If the comparisons are always integers (or an enumerated type) you can use a case statement.

    CASE example_int OF
        1,2: <do whatever you need to do>
        4,5,7,8: <do other stuff>
    ELSE
        <do default case stuff>
    END_CASE

If you need larger ranges you'll just have to use AND or nested IFs (nested IFs shown below)

   IF example_int >= 2 THEN
       IF example_int < 5 THEN
           //in range 2 - 5
       ELSIF example_int <= 10 THEN
           //in range 6 - 10
       END_IF
   END_IF

Remember to be mindful of the end points. If you forget the "or-equals" portion in either of the IF statements above, it changes the range

Alex Marks
  • 66
  • 7
0

There is no other way to check if the condition is ok like you want to do. In ST, you can code Library & function, if you have too much condition, you can code a library who resolve your problem. But it's useless because ST allow to order code to be readable. Like below :

IF (n>=0) AND (n<=20)  OR
   (n>=32) AND (n<=45) THEN
// Do this
ELSE
// Do that
END_IF ;

But you can call a function or library to fill a boolean var with TRUE or FALSE. You will just need to test the var in a logic loop.


//IN_aTestValues & aValueToTest are an Array of values
bVarTest := TestCond( IN_aTestValues := aValueToTest );

If bVarTest THEN
// Do this
ELSE
// Do that
END_IF ;

You can also do :

bVar := bToTest = 67 AND
        bToTest = 84 AND
        bToTest > 47 AND
        NOT (bToTest = 25) ;

IF bVar THEN
// Do this
Else 
// Do That
END_IF ;