nil and Booleans
Prerequisites: Data types
nil
nil means "no value". Any variable or table field that was never set is
nil:
local x
print(x)
local user = {name = "Ada"}
print(user.name)
print(user.email)
nil
Ada
nil
Reading a missing field isn't an error — it gives nil. Setting a field
to nil removes it.
Only nil and false are false
In conditions, only nil and false count as false. Everything
else — including 0 and the empty string — is true:
local values = {0, "", "text", false}
for i = 1, 4 do
local v = values[i]
if v then
print(string.format("%q is truthy", tostring(v)))
else
print(string.format("%q is falsy", tostring(v)))
end
end
print(nil and "yes" or "no")
"0" is truthy
"" is truthy
"text" is truthy
"false" is falsy
no
This surprises people coming from Python or JavaScript, where 0 and ""
are false. In Lua, test explicitly: if count > 0, if name ~= "".
and / or return values
and and or return one of their operands, not just true/false:
print(nil or "default")
print("given" or "default")
print(false and "x")
print(1 and 2)
local name = nil
local display = name or "Guest"
print(display)
local age = 20
print(age >= 18 and "adult" or "minor")
default
given
false
2
Guest
adult
x or default— the standard way to give a default value.cond and a or b— Lua's version of a ternary operator. It fails ifaisnilorfalse(then you always getb), so use anifin that case.