Lua Booleans in Lua Emulating Ternary Operator with 'and' 'or' logical operators.


Example

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.

Syntax

condition and truthy_expr or falsey_expr

Use in variable assignment/initialization

local drink = (fruit == "apple") and "apple juice" or "water"

Use in table constructor

local menu =
{
  meal  = vegan and "carrot" or "steak",
  drink = vegan and "tea"    or "chicken soup"
}

Use as function argument

print(age > 18 and "beer" or "fruit punch")

Use in return statement

function get_gradestring(student)
  return student.grade > 60 and "pass" or "fail"
end

Caveat

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.