Learn/Lua/4. Making decisions
Lesson 4 of 8
Sign in

Lua, lesson 4

Making decisions

Programs need to choose: charge shipping only on small orders, warn when a battery is low. In Lua you make that choice with if.

if, elseif, else

The condition goes between if and then. The block ends with end. For more than two cases, add elseif branches (one word, no space):

Lua checks the conditions from top to bottom and runs only the first branch that matches. Both elseif and else are optional, but there is always exactly one end.

Comparison operators

OperatorMeaning

2 exercises to try what you just read.

Exercise 1

What's the weather like?

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

==equal
~=not equal (a tilde, not !=)
< <= > >=ordering

Comparisons give true or false. Be careful: Lua never converts between strings and numbers when comparing. "10" == 10 is false, and "10" < 5 is an error. Convert input with tonumber (or read it with io.read("n")) before comparing.

and, or, not

Lua spells the boolean operators as words:

and and or short-circuit: if the left side decides the answer, the right side is not evaluated.

What counts as true

This is the rule that surprises people coming from other languages: in Lua, only false and nil are false. Everything else is true, including 0 and the empty string "".

The and/or idiom

and and or don't just return true or false; they return one of their operands. a or b gives a if it is true, otherwise b. That gives you two handy idioms:

The second one works as long as the middle value isn't false or nil. Here 0 is fine, because 0 is true in Lua.

Further reading

  • Lua 5.5 Reference Manual: Control structures
  • Lua 5.5 Reference Manual: Relational operators
  • Lua 5.5 Reference Manual: Logical operators

Read a whole-number temperature in Celsius and print one word describing it:

  • below 0: freezing
  • 0 to 15: cold
  • 16 to 25: mild
  • above 25: hot

Sample input:

Sample output:

A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400. Read a year and print either <year> is a leap year or <year> is not a leap year.

Sample input:

Sample output:

local battery = 12
if battery < 20 then
  print("Low battery!")
  print("Plug in soon.")
else
  print("Battery OK")
end
if score >= 90 then
  print("A")
elseif score >= 80 then
  print("B")
else
  print("C or below")
end
if age >= 13 and age <= 19 then print("teen") end
if day == "Sat" or day == "Sun" then print("weekend") end
if not is_open then print("closed") end
if 0 then print("0 is true in Lua!") end
local name = input_name or "guest"            -- default value when input_name is nil
local fee = (total >= 50) and 0 or 5          -- like a one-line if/else
18
mild
2024
2024 is a leap year