Variables store values that later expressions can reuse.

local Use `local` to keep a variable inside the current file or block.

Variables

unitPrice
variables.lua
Replay: real traced execution (multi-file project)
local unitPrice = 12
local quantity = 3
local total = unitPrice * quantity

print("unit=" .. unitPrice)
print("total=" .. total)
local unitPrice = 8
local quantity = 3
local total = unitPrice * quantity

print("unit=" .. unitPrice)
print("total=" .. total)
local unitPrice = 20
local quantity = 3
local total = unitPrice * quantity

print("unit=" .. unitPrice)
print("total=" .. total)
  1. unitPrice ← 12, quantity ← 3, total ← 36

    1local unitPrice→ 12 = 12 --@unitPrice=8, 202local quantity→ 3 = 33local total→ 36 = unitPrice12 * quantity345print("unit=" .. unitPrice12)6print("total=" .. total36)
    outputunit=12
    total=36
  1. unitPrice ← 8, quantity ← 3, total ← 24

    1local unitPrice→ 8 = 82local quantity→ 3 = 33local total→ 24 = unitPrice8 * quantity345print("unit=" .. unitPrice8)6print("total=" .. total24)
    outputunit=8
    total=24
  1. unitPrice ← 20, quantity ← 3, total ← 60

    1local unitPrice→ 20 = 202local quantity→ 3 = 33local total→ 60 = unitPrice20 * quantity345print("unit=" .. unitPrice20)6print("total=" .. total60)
    outputunit=20
    total=60

What Happens

  1. unitPrice starts at 12.
  2. quantity starts at 3.
  3. total = unitPrice * quantity multiplies 12 * 3.
  4. total becomes 36.
  5. The program prints unit=12 and total=36.

Value Map

| unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |

Try It

Exercise: variables.lua

Reproduce unit=12 and total=36, then use the pinned unitPrice values 8 and 20 to predict each total.