TExcelTAD
Home › Lua › Lua If Statements

Lua If Statements

An if statement runs a block only when a condition is true. Lua's form is if … then … end, with optional elseif and else branches.

lua · try it yourself
local battery = 15

if battery < 20 then
  print("Low battery, plug in soon")
end

if battery > 50 then
  print("Plenty left")
else
  print("Less than half")
end
Low battery, plug in soon
Less than half

elseif chains

Write elseif as one word. The branches are tested from top to bottom, and only the first matching one runs:

lua · try it yourself
local function grade(score)
  if score >= 90 then
    return "A"
  elseif score >= 80 then
    return "B"
  elseif score >= 70 then
    return "C"
  else
    return "F"
  end
end

for _, s in ipairs({ 95, 83, 70, 42 }) do
  print(s, grade(s))
end
95	A
83	B
70	C
42	F

Note: else if (two words) is legal but starts a nested if that needs its own end. Forgetting it gives the error "'end' expected".

Conditions and truthiness

Any value can be a condition. Only nil and false count as false, so 0 and "" are true. This makes checking for "missing" values short:

lua · try it yourself
local user = { name = "Mia", email = nil }

if user.email then
  print("Send mail to " .. user.email)
else
  print(user.name .. " has no email")
end

local count = 0
if count then print("0 is true in Lua!") end
if count == 0 then print("compare explicitly for zero") end
Mia has no email
0 is true in Lua!
compare explicitly for zero

Combining conditions

Use and, or and not. Parentheses make intent clear:

lua · try it yourself
local age, hasTicket, isVip = 17, true, false

if age >= 18 and hasTicket then
  print("Welcome")
elseif isVip or (hasTicket and age >= 16) then
  print("Welcome with a guardian")
else
  print("Sorry")
end

if not isVip then print("Regular entrance") end
Welcome with a guardian
Regular entrance

The "ternary" idiom

Lua has no ?: operator. For simple cases, cond and x or y works as long as x is never nil or false:

lua · try it yourself
local temperature = 28
local advice = temperature > 25 and "shorts" or "jeans"
print(advice)

-- the pitfall: x is false
local flag = true and false or "fallback"
print(flag)
shorts
fallback

No switch statement

Lua has no switch. Use an elseif chain, or, when you map values to results, a table lookup, which is often clearer and faster:

lua · try it yourself
local handlers = {
  start = function() return "Starting engine" end,
  stop  = function() return "Stopping engine" end,
}

local function command(name)
  local handler = handlers[name]
  if handler then
    return handler()
  end
  return "Unknown command: " .. name
end

print(command("start"))
print(command("fly"))
Starting engine
Unknown command: fly

Common mistakes

Mistake Fix
if x = 5 then use == for comparison
if x != 5 then Lua writes ~=
if x > 5 (no then) add then
else if without a second end write elseif
if count then to test for zero if count == 0 then

Test yourself

How is "else if" written as one branch of an if chain?

  1. else if
  2. elif
  3. elseif
  4. elsif

Does if 0 then print("yes") end print yes?

  1. Yes
  2. No
  3. It is a syntax error
  4. Only in Lua 5.1

What is the usual Lua replacement for a switch on string values?

  1. A goto table
  2. A table that maps each value to a result or function
  3. string.switch
  4. There is none