Lua Booleans in Lua Truth tables


Example

Logical operators in Lua don't "return" boolean, but one of their arguments. Using nil for false and numbers for true, here's how they behave.

print(nil and nil)       -- nil
print(nil and 2)         -- nil
print(1 and nil)         -- nil
print(1 and 2)           -- 2

print(nil or nil)        -- nil
print(nil or 2)          -- 2
print(1 or nil)          -- 1
print(1 or 2)            -- 1

As you can see, Lua will always return the first value that makes the check fail or succeed. Here's the truth tables showing that.

  x  |  y  || and            x  |  y  || or
------------------         ------------------
false|false||  x           false|false||  y   
false|true ||  x           false|true ||  y   
true |false||  y           true |false||  x   
true |true ||  y           true |true ||  x

For those who need it, here's two function representing these logical operators.

function exampleAnd(value1, value2)
  if value1 then
    return value2
  end
  return value1
end

function exampleOr(value1, value2)
  if value1 then
    return value1
  end
  return value2
end