Values and Types
Booleans and Nil
Booleans represent true-or-false answers, while nil marks a missing value.
nil
`nil` means a variable has no useful value yet.
Booleans and Nil
booleans_nil.lua
Replay: real traced execution (multi-file project)
local stock = 0
local hasStock = stock > 0
local label = nil
if hasStock then
label = "ready"
else
label = "empty"
end
print("stock=" .. stock)
print("hasStock=" .. tostring(hasStock))
print("label=" .. label)
local stock = 2
local hasStock = stock > 0
local label = nil
if hasStock then
label = "ready"
else
label = "empty"
end
print("stock=" .. stock)
print("hasStock=" .. tostring(hasStock))
print("label=" .. label)
local stock = 5
local hasStock = stock > 0
local label = nil
if hasStock then
label = "ready"
else
label = "empty"
end
print("stock=" .. stock)
print("hasStock=" .. tostring(hasStock))
print("label=" .. label)
stock ← 0, hasStock ← false, label ← nil
1local stock→ 0 = 0 --@stock=2, 52local hasStock→ false = stock0 > 03local label→ nil = nillabel ← empty
6 label = "ready"7else8 label→ empty = "empty"9endprint("stock=" .. stock)
11print("stock=" .. stock0)12print("hasStock=" .. tostring(hasStockfalse))13print("label=" .. labelempty)outputstock=0 hasStock=false label=empty
stock ← 2, hasStock ← true, label ← nil
1local stock→ 2 = 22local hasStock→ true = stock2 > 03local label→ nil = nillabel ← ready
5if hasStocktrue then6 label→ ready = "ready"7elseprint("stock=" .. stock)
11print("stock=" .. stock2)12print("hasStock=" .. tostring(hasStocktrue))13print("label=" .. labelready)outputstock=2 hasStock=true label=ready
stock ← 5, hasStock ← true, label ← nil
1local stock→ 5 = 52local hasStock→ true = stock5 > 03local label→ nil = nillabel ← ready
5if hasStocktrue then6 label→ ready = "ready"7elseprint("stock=" .. stock)
11print("stock=" .. stock5)12print("hasStock=" .. tostring(hasStocktrue))13print("label=" .. labelready)outputstock=5 hasStock=true label=ready
Follow the Flag
stockstarts at0.hasStock = stock > 0becomesfalse.labelstarts asnil.- Because
hasStockis false,labelbecomesempty. - The program prints
stock=0,hasStock=false, andlabel=empty. | stock | hasStock | label | | --- | --- | --- | | 0 | false | empty | | 2 | true | ready | | 5 | true | ready |
Exercise: booleans_nil.lua
Reproduce label=empty, then use stock 2 and 5 to predict hasStock and label.