Lua knows three logical operators;
or. These operators are used to create conditional statements that return true or false. In Lua, false and nil are considered falsey, all other values are considered truthy.
not is a logic operator that will negate a boolean expression.
true will become
false and vice versa.
and is a logic operator that will evaluate two boolean expressions, and returns
true only when both expressions are
print(true and false)
print(true and true)
or is a logic operator that will return
true if any of the given two expressions are
print(false or false)
print(false or true)
In many languages it is possible to inline simple if-statements as expressions. For example, in Java, this can be done using the ternary operator. While such an operator does not exist in Lua, it can be simulated using a combination of the
or operators, by following the pattern
conditional and ifTrue or ifFalse. For instance:
local variable = true and "first" or "second"
local variable = false and "first" or "second"
This works because of short-circuit evaluation.
|Warning:||This doesn't act as a true ternary operator. If the "truthy" branch of the expression evaluates to false or nil, then the falsey branch will be returned instead. Therefore this works best if both values are constant.|