Logical Operators
- Aryn Wiebe
Logical operators (AND, OR, NOT) help evaluate conditions by determining if expressions are true or false, enabling more complex decision-making in your scripts.
The AND operator evaluates two operands and returns true only if both operands are non-zero or true.
It’s useful when you need to check multiple conditions and ensure all must be true for the result to proceed.
local isRainy = true
local hasUmbrella = true
local goOutside = isRainy and hasUmbrella
trace(goOutside) -- returns true
Since both isRainy
and hasUmbrella
are true, goOutside
is true. If either were false, goOutside
would be false.
The OR operator evaluates whether either of the two operands is non-zero, and if so, the condition becomes true.
It’s useful to set a default value. It's a concise way to say "use this value if it exists, otherwise use this default value.” It is also helpful when a nil value appears, you can avoid an error and assign a default value.
local isRainy = false
local P = {}
P.weather = isRainy or "No rain today"
trace(P.weather) -- returns "No rain today"
The NOT operator inverts the value of its operand. It returns true if the operand is false or nil and returns false if the operand is true.
It’s useful when you need to check for the opposite of a condition.
local isRainy = false
local noRain = not isRainy
trace(noRain) -- returns true
Since isRainy
is false, noRain
becomes true due to the NOT operator. If isRainy
were true, noRain
would be false.