An if statement lets Lua choose between branches.

if statement An `if` statement runs one block when its condition is true and can use `else` for the other case.

Conditionals

temperature
conditionals.lua
Replay: real traced execution (multi-file project)
local temperature = 72
local status = ""

if temperature >= 80 then
  status = "warm"
else
  status = "comfortable"
end

print("temperature=" .. temperature)
print("status=" .. status)
local temperature = 55
local status = ""

if temperature >= 80 then
  status = "warm"
else
  status = "comfortable"
end

print("temperature=" .. temperature)
print("status=" .. status)
local temperature = 90
local status = ""

if temperature >= 80 then
  status = "warm"
else
  status = "comfortable"
end

print("temperature=" .. temperature)
print("status=" .. status)
  1. temperature ← 72, status ← (empty)

    1local temperature→ 72 = 72 --@temperature=55, 902local status→ (empty) = ""
  2. status ← comfortable

    5  status = "warm"6else7  status→ comfortable = "comfortable"8end
  3. print("temperature=" .. temperature)

    10print("temperature=" .. temperature72)11print("status=" .. statuscomfortable)
    outputtemperature=72
    status=comfortable
  1. temperature ← 55, status ← (empty)

    1local temperature→ 55 = 552local status→ (empty) = ""
  2. status ← comfortable

    5  status = "warm"6else7  status→ comfortable = "comfortable"8end
  3. print("temperature=" .. temperature)

    10print("temperature=" .. temperature55)11print("status=" .. statuscomfortable)
    outputtemperature=55
    status=comfortable
  1. temperature ← 90, status ← (empty)

    1local temperature→ 90 = 902local status→ (empty) = ""
  2. status ← warm

    4if temperature90 >= 80 then5  status→ warm = "warm"6else
  3. print("temperature=" .. temperature)

    10print("temperature=" .. temperature90)11print("status=" .. statuswarm)
    outputtemperature=90
    status=warm

What Happens

  1. temperature starts at 72.
  2. Lua checks whether temperature >= 80.
  3. 72 >= 80 is false.
  4. The else branch sets status to comfortable.
  5. The program prints temperature=72 and status=comfortable.

Branch Picture

| temperature | comparison | status | | --- | --- | --- | | 55 | false | comfortable | | 72 | false | comfortable | | 90 | true | warm |

Try It

Exercise: conditionals.lua

Reproduce status=comfortable for temperature 72, then use the pinned temperatures 55 and 90 to identify each branch.