Logic
Lua knows three logical operators; not
, and
, and 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.[1]
not
not is a logic operator that will negate a boolean expression. true
will become false
and vice versa.
print(not true)
will output false
.
print(not false)
will output true
.
and
and is a logic operator that will evaluate two boolean expressions, and returns true
only when both expressions are true
.
print(true and false)
will output false
.
print(true and true)
will output true
.
or
or is a logic operator that will return true
if any of the given two expressions are true
.
print(false or false)
will output false
print(false or true)
will output true
Conditional expressions
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.[2] While such an operator does not exist in Lua, it can be simulated using a combination of the and
and or
operators, by following the pattern conditional and ifTrue or ifFalse
. For instance:
<nowiki>local variable = true and "first" or "second"</nowiki>
will initialise variable
with "first"
.
<nowiki>local variable = false and "first" or "second"</nowiki>
will initialise variable
with "second"
.
This works because of short-circuit evaluation.
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. |
References
- Ierusalimschy, Roberto (March 2006). Programming in Lua. p. 40. ISBN 8590379825.
- "Equality, Relational, and Conditional Operators". Retrieved 2018-08-14.