Lesson 3 of 8 · 7 min

Decisions

local temp = 28

if temp > 30 then
  print("Hot")
elseif temp >= 20 then
  print("Warm")
else
  print("Cold")
end

Lua uses words instead of braces: then after the condition, and end to close the whole if.

Comparisons: ==, ~= (not equal: note the tilde), <, >, <=, >=.

Combine conditions with and, or and not:

if age >= 13 and age <= 19 then print("Teenager") end

nil and truthiness

nil means "no value". In a condition, only nil and false count as false; everything else is true, even 0 and empty text. That is different from many languages.

Reading input

io.read() reads one line of input as text. Here, input comes from the box above the Run button. tonumber(text) converts text to a number, or gives nil if it cannot:

local age = tonumber(io.read())
if age == nil then
  print("That is not a number")
end

Your task

Read a temperature and print:

  • Please enter a number if the input is not a number,
  • Hot above 30,
  • Warm from 20 to 30,
  • Cold below 20.
main.lua
local temp = tonumber(io.read())

-- decide what to print

Lua 5.4 runs right here in your browser. The first run downloads about 0.4 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…