Lua Booleans in Lua Logical Operators


Example

In Lua, booleans can be manipulated through logical operators. These operators include not, and, and or.

In simple expressions, the results are fairly straightforward:

print(not true) --> false
print(not false) --> true
print(true or false) --> true
print(false and true) --> false

Order of Precedence

The order of precedence is similar to the math operators unary -, * and +:

  • not
  • then and
  • then or

This can lead to complex expressions:

print(true and false or not false and not true)
print( (true and false) or ((not false) and (not true)) )
    --> these are equivalent, and both evaluate to false

Short-cut Evaluation

The operators and and or might only be evaluated using the first operand, provided the second is unnecessary:

function a()
    print("a() was called")
    return true
end

function b()
    print("b() was called")
    return false
end

print(a() or b())
    --> a() was called
    --> true
    --  nothing else
print(b() and a())
    --> b() was called
    --> false
    --  nothing else
print(a() and b())
    --> a() was called
    --> b() was called
    --> false

Idiomatic conditional operator

Due to the precedence of the logical operators, the ability for short-cut evaluation and the evaluation of non-false and non-nil values as true, an idiomatic conditional operator is available in Lua:

function a()
    print("a() was called")
    return false
end
function b()
    print("b() was called")
    return true
end
function c()
    print("c() was called")
    return 7
end

print(a() and b() or c())
    --> a() was called
    --> c() was called
    --> 7
    
print(b() and c() or a())
    --> b() was called
    --> c() was called
    --> 7

Also, due to the nature of the x and a or b structure, a will never be returned if it evaluates to false, this conditional will then always return b no matter what x is.

print(true and false or 1)  -- outputs 1