Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 32 ยท Values and Operators

Operators and Truthiness

Learn Lua operators: comparison, and, or, not with short-circuit rules, why only nil and false are falsy, the a and b or c idiom, and operator precedence.

Operators combine values into new values. Most of Lua's operators will feel familiar, but three details surprise newcomers: and and or return one of their operands instead of a boolean, only nil and false count as false (so 0 and the empty string are true), and ~= is the "not equal" operator. Once you understand these, a large part of idiomatic Lua code becomes easy to read.

This lesson reviews arithmetic and comparison operators briefly, then spends most of its time on logical operators, truthiness, the popular a and b or c idiom and its pitfall, and the precedence table. Arithmetic itself was covered in Numbers and the math Library and joining text in Strings.

Arithmetic and comparison

The arithmetic operators are + - * / // % ^, plus unary minus. Lua has no ++, -- or +=; write n = n + 1. The comparison operators are ==, ~=, <, <=, > and >=, and they always produce a boolean.

LUA
print(3 == 3.0)        --> true
print("a" ~= "b")      --> true
print(2 < 5)           --> true
print("apple" < "banana")   --> true
print(nil == false)    --> false
print({} == {})        --> false

Rules worth remembering:

  • == never converts types. 1 == "1" is false.
  • An integer and a float with the same value are equal: 1 == 1.0 is true.
  • Tables, functions and other objects are compared by identity: two separate empty tables are never equal, but a table is equal to itself.
  • < and friends work on two numbers or two strings. Mixing types raises an error: 1 < "2" fails with "attempt to compare number with string".
  • String comparison is lexicographic, so "10" < "9" is true. Convert with tonumber first when you mean numeric order.

Truthiness: only nil and false are false

In a condition, Lua treats nil and false as false and everything else as true. That includes 0, 0.0, the empty string "" and an empty table.

What counts as false?

nil Falsy.
false Falsy.

Those two are the only falsy values in Lua.

1 / 2
LUA
if 0 then print("zero is true") end         --> zero is true
if "" then print("empty string is true") end --> empty string is true
if {} then print("empty table is true") end  --> empty table is true
if nil then print("never printed") end

If you come from JavaScript, Python or C, this is the difference to learn first. In Lua you cannot write if count then to mean "count is not zero". You write if count ~= 0 then.

The logical operators

not returns a real boolean: true for nil and false, false for everything else.

and and or are short-circuit operators that return one of their operands.

  • a and b returns a if a is false, otherwise it returns b.
  • a or b returns a if a is true, otherwise it returns b.

The right operand is only evaluated when it is needed.

LUA
print(not nil)          --> true
print(not 0)            --> false
print(nil and 1)        --> nil
print(false and 1)      --> false
print(1 and 2)          --> 2
print(1 or 2)           --> 1
print(nil or "default") --> default
print(false or nil)     --> nil

Short-circuiting means the second expression may never run, which is both a performance tool and a safety tool.

LUA
local user = nil
local name = user and user.name        -- no error: user.name is skipped
print(name)                            --> nil

local function log(msg) print("log: " .. msg); return true end
local ok = false and log("hidden")     -- log is never called

Default values with or

The most common use of or is supplying a default.

LUA
local function greet(name)
  name = name or "stranger"
  print("Hello, " .. name)
end
greet("Ada")     --> Hello, Ada
greet()          --> Hello, stranger

Be careful when the legitimate value can be false. If verbose is false on purpose, verbose = verbose or true would turn it back into true. In that case test explicitly: if verbose == nil then verbose = true end.

The a and b or c idiom and its pitfall

Lua has no ternary operator, but cond and a or b works like one.

LUA
local age = 20
local label = age >= 18 and "adult" or "minor"
print(label)    --> adult

It works because cond and a is a when cond is true and false/nil otherwise, and then or b picks b when the left part is false or nil. The pitfall: if a itself is nil or false, the whole expression falls through to b even when cond is true.

LUA
local flag = true
local result = flag and false or "fallback"
print(result)   --> fallback   (probably not what you wanted)

When the "true" branch might be false or nil, use a regular if statement instead (the next lesson, Conditionals, shows the forms).

Precedence

When an expression mixes operators, Lua applies them in this order, from the lowest priority to the highest:

Level Operators
1 (lowest) or
2 and
3 < > <= >= ~= ==
4 |
5 ~ (binary xor)
6 &
7 << >>
8 .. (right associative)
9 + -
10 * / // %
11 unary not # - ~
12 (highest) ^ (right associative)

Some consequences:

LUA
print(1 + 2 .. 3 + 4)      --> 37   (arithmetic first, then join "3" and "7")
print("a" .. "b" == "ab")  --> true (.. binds tighter than ==)
print(not nil == true)     --> true ((not nil) == true)
print(-2 ^ 2)              --> -4.0 (^ binds tighter than unary minus)
print(2 ^ 3 ^ 2)           --> 512.0 (2 ^ (3 ^ 2))
print(1 < 2 == true)       --> true ((1 < 2) == true)
print(nil or false and 1)  --> false (and binds tighter than or)

You do not have to memorize the table. When an expression is not obvious, add parentheses. Readable code beats clever code.

Stand-ins you can run

JavaScript's && and || also return operands, but they treat 0, "", NaN and null as false. The first stand-in implements Lua's rules with small helper functions. The right-hand side is passed as a function so we can show short-circuiting.

JS Lua truthiness and short-circuit operators (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in shows the a and b or c idiom and the false-branch pitfall, plus a few precedence results.

JS The ternary idiom and precedence (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which values are false in a Lua condition?

    Lua treats only nil and false as false. Zero, empty strings and empty tables are all true.
  2. 2. What does print(nil or "default") print?

    or returns its first operand when that operand is true, otherwise the second. nil is false, so the result is the string default.
  3. 3. What does print(false and error("boom")) do?

    and short-circuits: the left operand is false, so it is returned and error is never called.
  4. 4. What is the value of true and false or "fallback"?

    true and false is false, and then false or "fallback" yields the second operand. This is the pitfall of the a and b or c idiom.
  5. 5. What does -2 ^ 2 evaluate to?

    The ^ operator has higher precedence than unary minus, so this is -(2 ^ 2), and ^ always gives a float.

Summary

  • Comparisons never convert types, tables compare by identity, and ~= means not equal.
  • Only nil and false are falsy; 0, "" and {} are truthy.
  • and and or short-circuit and return one of their operands; not always returns a boolean.
  • x = x or default supplies defaults, but fails when false is a valid value; cond and a or b fails when a is falsy.
  • ^ binds tightest, then unary operators, then arithmetic, .., comparisons, and and or; use parentheses when in doubt.

Next: choose between paths with Conditionals.