Conditional operators in Lua

In Lua, conditional statements execute a set of commands for one or more logical conditions. This is commonly used to validate variables.


The code is executed only if a predetermined condition is true. You can write as a single string, and split into multiple lines, it depends on your style and readability of the code.

In the condition, you can insert variables and the following comparison operators.

== Equal
~ = not equal to
<less than
<= less than or equal
to> greater than
> = greater than or equal

For example, if we need to check that the variable f is greater than zero, then use the following code.

The condition is acceptable to take in brackets ( ), so the entry below is identical to the top post. You can choose the option that is more like it.

For more complicated cases,  apply an else statement, as shown below.

When you want to check for multiple conditions, use the elseif statement.

In this example, if the variable is equal to the “+” operator, then add up the variables a and b, and their sum is assigned to r. Further, in this case, the code is ignored. If the operator is not equal to “+“, then turns to verify what it is and the corresponding operation is performed. If the value of the operator is not defined, or we have not specified a suitable option, it will display the text “Invalid operator“.

For more complex conditions apply logical operators and (ii) and or (OR). For example, we have verified that the number N is inclusive in the range from 0 to 10. Then place the following condition.

In this case, we check that N is greater than or equal to 0 and less than or equal to 10.

The logical or is used when we have to choose one of the options, but not both. For example, to execute some code if x or y is equal to 5. Then the code would be as follows: