Object Patterns with Tables
Copy Update
Model updating an object-style value by calculating a new scalar state.
copy update
Instead of mutating a table in place, calculate the next value from the current field and keep the result explicit.
Copy Update
copy_update.lua
Replay: real traced execution (multi-file project)
local stock = 5
local sold = 3
local remaining = ({stock = stock}).stock - sold
local status = "available"
if remaining <= 0 then
status = "empty"
end
print("stock=" .. stock)
print("remaining=" .. remaining)
print("status=" .. status)
local stock = 0
local sold = 3
local remaining = ({stock = stock}).stock - sold
local status = "available"
if remaining <= 0 then
status = "empty"
end
print("stock=" .. stock)
print("remaining=" .. remaining)
print("status=" .. status)
local stock = 9
local sold = 3
local remaining = ({stock = stock}).stock - sold
local status = "available"
if remaining <= 0 then
status = "empty"
end
print("stock=" .. stock)
print("remaining=" .. remaining)
print("status=" .. status)
stock ← 5, sold ← 3, remaining ← 2, status ← available
1local stock→ 5 = 5 --@stock=0, 92local sold→ 3 = 33local remaining→ 2 = ({stock = stock}).stock5 - sold34local status→ available = "available"5if remaining <= 0 then6 status = "empty"7end8print("stock=" .. stock5)9print("remaining=" .. remaining2)10print("status=" .. statusavailable)outputstock=5 remaining=2 status=available
stock ← 0, sold ← 3, remaining ← -3, status ← available
1local stock→ 0 = 02local sold→ 3 = 33local remaining→ -3 = ({stock = stock}).stock0 - sold34local status→ available = "available"5if remaining <= 0 thenstatus ← empty
4local status = "available"5if remaining-3 <= 0 then6 status→ empty = "empty"7endprint("stock=" .. stock)
7end8print("stock=" .. stock0)9print("remaining=" .. remaining-3)10print("status=" .. statusempty)outputstock=0 remaining=-3 status=empty
stock ← 9, sold ← 3, remaining ← 6, status ← available
1local stock→ 9 = 92local sold→ 3 = 33local remaining→ 6 = ({stock = stock}).stock9 - sold34local status→ available = "available"5if remaining <= 0 then6 status = "empty"7end8print("stock=" .. stock9)9print("remaining=" .. remaining6)10print("status=" .. statusavailable)outputstock=9 remaining=6 status=available