Logical operators
and, or and not work on truthiness and give you short-circuit values, not only true or false.
In this page:
Logical operators
The operator and returns its first operand if that is falsy, otherwise its second. The operator or returns its first operand if it is truthy, otherwise its second. Because of this, a and b or c acts like a ternary conditional, and x or default supplies a default value. not always returns a real boolean.
Note:
The and/or ternary fails when the middle value can be false or nil, so use if in that case.
Example: Logical operators
print(nil or "default", false and "never")
print(1 and 2, nil and 2, 0 or 5)
local age = 20
print(age >= 18 and "adult" or "minor")
print(not nil, not 0)
print(false and nil or "fallthrough")
-- Output:
-- default false
-- 2 nil 0
-- adult
-- true false
-- fallthrough
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting and/or to always return booleans
- Using a and b or c when b may be false
- Using && and || from other languages
Chapter Summary
- and returns its first falsy operand or the last one
- or returns its first truthy operand
- x or default gives a default value
- not always gives a boolean
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: