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

stock
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)
  1. stock ← 0, hasStock ← false, label ← nil

    1local stock→ 0 = 0 --@stock=2, 52local hasStock→ false = stock0 > 03local label→ nil = nil
  2. label ← empty

    6  label = "ready"7else8  label→ empty = "empty"9end
  3. print("stock=" .. stock)

    11print("stock=" .. stock0)12print("hasStock=" .. tostring(hasStockfalse))13print("label=" .. labelempty)
    outputstock=0
    hasStock=false
    label=empty
  1. stock ← 2, hasStock ← true, label ← nil

    1local stock→ 2 = 22local hasStock→ true = stock2 > 03local label→ nil = nil
  2. label ← ready

    5if hasStocktrue then6  label→ ready = "ready"7else
  3. print("stock=" .. stock)

    11print("stock=" .. stock2)12print("hasStock=" .. tostring(hasStocktrue))13print("label=" .. labelready)
    outputstock=2
    hasStock=true
    label=ready
  1. stock ← 5, hasStock ← true, label ← nil

    1local stock→ 5 = 52local hasStock→ true = stock5 > 03local label→ nil = nil
  2. label ← ready

    5if hasStocktrue then6  label→ ready = "ready"7else
  3. print("stock=" .. stock)

    11print("stock=" .. stock5)12print("hasStock=" .. tostring(hasStocktrue))13print("label=" .. labelready)
    outputstock=5
    hasStock=true
    label=ready

Follow the Flag

  1. stock starts at 0.
  2. hasStock = stock > 0 becomes false.
  3. label starts as nil.
  4. Because hasStock is false, label becomes empty.
  5. The program prints stock=0, hasStock=false, and label=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.