Lua Booleans in Lua The boolean type

Booleans and other values

When dealing with lua it is important to differentiate between the boolean values true and false and values that evaluate to true or false.

There are only two values in lua that evaluate to false: nil and false, while everything else, including the numerical 0 evaluate to true.

Some examples of what this means:

if 0 then print("0 is true") end --> this will print "true"
if (2 == 3) then print("true") else print("false") end --> this prints "false"
if (2 == 3) == false then print("true") end --> this prints "true"
if (2 == 3) == nil then else print("false") end
--> prints false, because even if nil and false both evaluate to false,
--> they are still different things.

Logical Operations

Logical operators in lua don't necessarily return boolean values:

and will return the second value if the first value evaluates to true;

or returns the second value if the first value evaluates to false;

This makes it possible to simulate the ternary operator, just like in other languages:

local var = false and 20 or 30 --> returns 30
local var = true and 20 or 30 --> returns 20
-- in C: false ? 20 : 30

This can also be used to initialize tables if they don't exist

tab = tab or {} -- if tab already exists, nothing happens

or to avoid using if statements, making the code easier to read

print(debug and "there has been an error") -- prints "false" line if debug is false
debug and print("there has been an error") -- does nothing if debug is false
-- as you can see, the second way is preferable, because it does not output
-- anything if the condition is not met, but it is still possible.
-- also, note that the second expression returns false if debug is false,
-- and whatever print() returns if debug is true (in this case, print returns nil)

Checking if variables are defined

One can also easily check if a variable exists (if it is defined), since non-existant variables return nil, which evaluates to false.

local tab_1, tab_2 = {}
if tab_1 then print("table 1 exists") end --> prints "table 1 exists"
if tab_2 then print("table 2 exists") end --> prints nothing

The only case where this does not apply is when a variable stores the value false, in which case it technically exists but still evaluates to false. Because of this, it is a bad design to create functions which return false and nil depending on the state or input. We can still check however whether we have a nil or a false:

if nil == nil then print("A nil is present") else print("A nil is not present") end
if false == nil then print("A nil is present") else print("A nil is not present") end
-- The output of these calls are:
-- A nil is present!
-- A nil is not present PDF - Download Lua for free