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

nil and booleans

nil means no value, and only nil and false count as false in a condition.

In this page:

  1. nil and booleans

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

lua
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
Common Mistakes
  1. Assuming 0 is false
  2. Assuming an empty string is false
  3. 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:

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.