How to use logical operators in Lua
In Lua, we have and, or, and not as logical operators. These operators can be used to evaluate the expression.
In Lua, everything that is not
nilorfalseis handled astruein logical expressions.
The and operator
The and operator is used as a binary and returns the first operand if it’s false. Otherwise, it will return the second.
Example
print('a string' and false)print('a string' and true)print(true and 12)
Expected output
false
true
12
The or operator
The or operator returns the first operand if it’s true. Otherwise, it returns the second.
Example
print("a" or false)print(true or 1)
Expected output
a
true
The not operator
The not operator is a unary operator and will return true if the operand is nil or false. Otherwise, it will return true.
Example
print(not false)print(not true)print(not 11)
Expected output
true
false
false