Tables Are Shared
With numbers and texts, = copies the value. After local b = a, changing b doesn't change a:
local a = 5
local b = a
b = b + 1
print(a, b)5 6Tables behave differently. A variable doesn't hold the table itself, only a reference to it: something like the address of the table in the computer's memory. That's the 0x… in what print(t) prints. local b = a copies the reference, not the table, so both variables lead to the same table:
local prices = {carrot = 5, potato = 8}
local joePrices = prices
joePrices.carrot = 6
print(prices.carrot)
print(prices == joePrices)6
trueGrandpa Joe changed “his” price, and Emma's changed too, because there is only one table with two names. And == on tables asks whether it's the same table, not whether two tables have the same contents. Each {} creates a new table, so:
print({} == {})
print({carrot = 5} == {carrot = 5})false
falseTo compare the contents of two tables, compare their keys and values yourself, for example in a loop.
The same thing happens when you pass a table to a function. The parameter refers to the same table, so the function can change it, and the change is visible outside. That's often what you want; such a function doesn't even have to return anything:
local function harvest(barn, crop, amount)
barn[crop] = (barn[crop] or 0) + amount
end
local barn = {}
harvest(barn, "carrot", 12)
harvest(barn, "carrot", 3)
print(barn.carrot)15When you want a separate table, you have to copy it: create a new table and copy every key and value into it with pairs:
local function copy(t)
local result = {}
for key, value in pairs(t) do
result[key] = value
end
return result
end
local prices = {carrot = 5, potato = 8}
local joePrices = copy(prices)
joePrices.carrot = 6
print(prices.carrot, joePrices.carrot)
print(prices == joePrices)5 6
falseThe function works for lists too, because pairs also goes through the keys 1, 2, 3… But it copies only one level: when a value is itself a table, like the barn in farm.barn, the copy gets a reference to the same inner table.
Instructions
Run the program: Emma's prices have changed too, because hugoPrices is the same table as prices. Write a function copy(t) that returns a new table with the same keys and values, and make hugoPrices a copy of prices. The program then prints:
Emma: carrot 5, potato 8, pumpkin 20
Hugo: carrot 7, potato 8, pumpkin 25At the end of the program, write a function raise(t, amount) that adds amount to every price in the table it gets: it changes that table and returns nothing. Raise Hugo's prices by 1 and show both price lists again:
Emma: carrot 5, potato 8, pumpkin 20
Hugo: carrot 8, potato 9, pumpkin 26Start programming for free
9/10