nil and booleans
nil means no value, and only nil and false count as false in a condition.
In this page:
nil and booleans
nil is the type of the absent value, and assigning nil to a variable or table field removes it. The booleans are true and false. In conditions only nil and false are falsy, so 0 and the empty string are both truthy.
Note:
Compare with nil explicitly, as in x == nil, when false and nil must be told apart.
Example: nil and booleans
local function truthy(v)
if v then return "truthy" else return "falsy" end
end
print(truthy(nil), truthy(false))
print(truthy(0), truthy(""))
print(type(nil), type(false))
print(nil == false)
-- Output:
-- falsy falsy
-- truthy truthy
-- nil boolean
-- false
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Assuming 0 is false
- Assuming an empty string is false
- Confusing false with nil when they behave differently
Chapter Summary
- nil means no value
- Only nil and false are falsy
- 0 and "" are truthy
- Unassigned variables are nil
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: