Foundations
Conditionals
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
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)
temperature ← 72, status ← (empty)
1local temperature→ 72 = 72 --@temperature=55, 902local status→ (empty) = ""status ← comfortable
5 status = "warm"6else7 status→ comfortable = "comfortable"8endprint("temperature=" .. temperature)
10print("temperature=" .. temperature72)11print("status=" .. statuscomfortable)outputtemperature=72 status=comfortable
temperature ← 55, status ← (empty)
1local temperature→ 55 = 552local status→ (empty) = ""status ← comfortable
5 status = "warm"6else7 status→ comfortable = "comfortable"8endprint("temperature=" .. temperature)
10print("temperature=" .. temperature55)11print("status=" .. statuscomfortable)outputtemperature=55 status=comfortable
temperature ← 90, status ← (empty)
1local temperature→ 90 = 902local status→ (empty) = ""status ← warm
4if temperature90 >= 80 then5 status→ warm = "warm"6elseprint("temperature=" .. temperature)
10print("temperature=" .. temperature90)11print("status=" .. statuswarm)outputtemperature=90 status=warm
What Happens
temperaturestarts at72.- Lua checks whether
temperature >= 80. 72 >= 80is false.- The
elsebranch setsstatustocomfortable. - The program prints
temperature=72andstatus=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.