In lua, the logical operators and
and or
returns one of the operands as the result instead of a boolean result. As a consequence, this mechanism can be exploited to emulate the behavior of the ternary operator despite lua not having a 'real' ternary operator in the language.
condition and truthy_expr or falsey_expr
local drink = (fruit == "apple") and "apple juice" or "water"
local menu =
{
meal = vegan and "carrot" or "steak",
drink = vegan and "tea" or "chicken soup"
}
print(age > 18 and "beer" or "fruit punch")
function get_gradestring(student)
return student.grade > 60 and "pass" or "fail"
end
There are situations where this mechanism doesn't have the desired behavior. Consider this case
local var = true and false or "should not happen"
In a 'real' ternary operator, the expected value of var
is false
. In lua, however, the and
evaluation 'falls through' because the second operand is falsey. As a result var
ends up with should not happen
instead.
Two possible workarounds to this problem, refactor this expression so the middle operand isn't falsey. eg.
local var = not true and "should not happen" or false
or alternatively, use the classical if
then
else
construct.