Lua Truthiness
Truthiness is how Lua decides whether a value counts as true or false in a check. Lua is strict here, and only two values count as false.
Zero counts as true
Each line tests a zero value with and and or. Both lines print yes, which proves that zero counts as true.
print(0 and "yes" or "no")
print(0.0 and "yes" or "no")Empty text counts as true
The empty string holds no characters, but it is still a real value. The test prints yes for it, just like for ordinary text.
print("" and "yes" or "no")
print("hello" and "yes" or "no")Only false and nil count as false
The same test prints no for both false and nil. The last line shows or stepping in with a fallback when the first value is nil.
print(false and "yes" or "no")
print(nil and "yes" or "no")
print(nil or "fallback")Example
local score = 0
local name = ""
local saved = nil
print(score and "score counts" or "score missing")
print(name and "name counts" or "name missing")
print(saved and "saved counts" or "saved missing")Key points
- Falsy values: only false and nil count as false.
- Truthy values: every other value counts as true.
- Zero: 0 and 0.0 both count as true.
- Empty text: the empty string "" counts as true.
- Showing it: value and "yes" or "no" prints yes when the value counts as true and no when it counts as false.
In this example, three values are tested with the same and and or pattern. The score of 0 counts as true and the empty name counts as true, so both lines print the counts message. The saved value is nil, which counts as false, so its line prints the missing message.
Note
many languages treat 0 as false, but Lua treats it as true.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which list contains only the falsy values in Lua?