← Back to Lua Course | Chapter 2: Variables & Types | Lesson 7 of 7

Logical operators

and, or and not work on truthiness and give you short-circuit values, not only true or false.

In this page:

  1. Logical operators

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

lua
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
Common Mistakes
  1. Expecting and/or to always return booleans
  2. Using a and b or c when b may be false
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.