Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 32 ยท Control Flow

Conditionals

Make decisions in Lua with if, elseif and else, nest conditions cleanly, and replace the missing switch statement with a table of functions.

Programs get interesting when they can choose between actions. In Lua the tool for that is the if statement. It looks a lot like the ones in Pascal or Ruby: words instead of braces, and an end to close the block. If you came from C, Java or JavaScript, the missing parentheses and curly braces take a moment to get used to, but the rules are simple and there are very few of them.

This lesson covers if, elseif and else, how conditions are judged (remember: only nil and false count as false, see Operators and Truthiness), nesting, and what to do about the fact that Lua has no switch statement. Lua is not installed on this site, so the Lua code in read-only blocks is real Lua, and the runnable examples are JavaScript stand-ins that follow the same logic.

The basic if statement

An if needs a condition, the word then, a body, and end:

LUA
local temperature = 31

if temperature > 30 then
  print("It is hot outside.")
end

The condition can be any expression. Parentheses around it are allowed but unnecessary. Indentation is only for people, Lua ignores it, but two spaces per level is the common style.

else and elseif

Add else for the "otherwise" branch. Add elseif (one word, no space) for more tests. Lua checks the conditions from top to bottom and runs the first branch whose condition is true. All the rest are skipped:

LUA
local score = 72

if score >= 90 then
  print("A")
elseif score >= 80 then
  print("B")
elseif score >= 70 then
  print("C")
else
  print("Needs work")
end
-- prints: C

A chain of elseif needs only one end at the very bottom. A common beginner mistake is writing else if as two words. That is legal, but it opens a second, nested if that needs its own end:

LUA
if score >= 90 then
  print("A")
else
  if score >= 80 then   -- a NEW if inside the else block
    print("B")
  end
end                      -- two ends needed

Prefer elseif whenever you mean a chain.

Anatomy of an if

Condition Any expression. Only nil and false fail.
then Starts the body. Never forget it.
elseif / else Optional extra branches, checked in order.
end One end closes the whole chain.
1 / 2

What counts as true

Every Lua value can be used as a condition. Only nil and false are false. Everything else is true, including 0, the empty string "" and an empty table {}:

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

This is different from JavaScript, Python and C, and it catches many newcomers. To test for an empty string, compare it: if name == "" then. To test whether a table has any entries, use next(t) == nil (an empty table has no first entry) or check #t == 0 for a sequence.

Comparison operators are ==, ~= (not equal, note the tilde, there is no !=), <, <=, > and >=. Combine tests with and, or and not:

LUA
local age, member = 17, true

if age >= 18 or member then
  print("welcome in")
end

if not (age >= 18) then
  print("minor")
end

and and or short-circuit: in a and b, b is evaluated only when a is truthy. That lets you guard a risky test:

LUA
local user = nil
if user and user.age > 18 then   -- user.age is never touched when user is nil
  print("adult")
end

Try it: grading with elseif

This stand-in uses JavaScript with the same branch order as the Lua chain above. The point to notice is that the first match wins, so the order of the tests matters.

JS elseif chain stand-in (JavaScript)

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

No output.

Nested conditions

You can put an if inside any branch. When the nesting gets deep, look for ways to flatten it with and, or return early from a function:

LUA
local function describe(n)
  if type(n) ~= "number" then
    return "not a number"
  end
  if n < 0 then
    return "negative"
  elseif n == 0 then
    return "zero"
  end
  return "positive"
end

print(describe("x"))  --> not a number
print(describe(-4))   --> negative
print(describe(9))    --> positive

Early returns (sometimes called guard clauses) keep the main path of the function at one level of indentation. You will meet functions properly in Functions.

One related trick is the a and b or c idiom, which behaves like a ternary operator. It is handy, but it fails when b is false or nil, because then c is returned. The details are in the operators lesson, so use an ordinary if whenever b might be falsy.

There is no switch

Lua deliberately has no switch or case. When you would write one, you have two good options. The first is a plain if/elseif chain, which is fine for a handful of branches:

LUA
local command = "stop"

if command == "start" then
  print("starting")
elseif command == "stop" then
  print("stopping")
else
  print("unknown command: " .. command)
end

The second is a dispatch table: a table whose keys are the values you would put in the case lines and whose values are functions. Looking up a key is fast, and adding a new case means adding a table entry, not editing a long chain:

LUA
local actions = {
  start = function() print("starting") end,
  stop  = function() print("stopping") end,
}

local command = "stop"
local action = actions[command]
if action then
  action()
else
  print("unknown command: " .. command)
end

Tables are covered in Tables as Arrays and Dictionaries; for now just read actions[command] as "look up the entry named by command". The result is nil when the key is missing, so checking if action then handles the default case.

Try it: a dispatch table

The JavaScript object below plays the role of the Lua table. Missing keys give undefined, which stands in for nil.

JS Dispatch table stand-in (JavaScript)

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

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

    Lua treats only nil and false as false. Zero, the empty string and empty tables are all true.
  2. 2. How many end keywords does if a then ... elseif b then ... else ... end need?

    An elseif chain is a single statement closed by a single end. Writing else if as two words would open a new, nested if that needs its own end.
  3. 3. Which operator means 'not equal' in Lua?

    Lua uses the tilde-equals operator ~= for inequality. There is no != in the language.
  4. 4. What is the usual replacement for a switch statement in Lua?

    Lua has no switch. Short cases use elseif, and larger ones use a dispatch table whose keys are the case values.

Summary

  • if cond then ... elseif cond then ... else ... end runs the first branch whose condition is true.
  • Write elseif as one word; else if nests a second if that needs its own end.
  • Only nil and false are false. 0, "" and {} are true.
  • Use ~= for "not equal" and and, or, not to combine tests; and and or short-circuit.
  • Guard clauses with early return keep nesting shallow.
  • There is no switch: use elseif chains or a table of functions.

Next, repeat actions with Loops.