Tables Are Shared, Not Copied

Look at this small program. What do you think it prints?

local a = {10, 20}
local b = a
b[1] = 99
print(a[1])

Output:

99

The code changed b, but a changed too. Now try the same steps with a number:

local score = 10
local copy = score
copy = 99
print(score)

Output:

10

This time score did not change. Why are the two results different?

Numbers, strings and booleans are copied. local copy = score puts its own 10 into copy. After that, the two variables are separate.

Tables are not copied. A table variable does not hold the table itself. It holds a reference, which tells Lua where the table is. local b = a copies only the reference. So a and b are two names for the same table:

  a ──┐
      ├──> {10, 20}
  b ──┘

Functions can change a table

The same rule applies when you pass a table to a function. The function gets a reference to your table, not a copy. So it can change your table:

function levelUp(player)
    player.level = player.level + 1
end

local alice = {name = "Alice", level = 3}
levelUp(alice)
print(alice.level)

Output:

4

levelUp does not return anything, but alice.level is now 4. This is useful, and it is how table.insert, table.remove and table.sort work: they change the table you give them. It also means you should know which of your functions change their tables. A clear name like levelUp helps.

Making a real copy

If you need a separate copy, make a new table and copy each value into it:

local a = {10, 20}
local b = {}
for i, v in ipairs(a) do
    b[i] = v
end
b[1] = 99
print(a[1], b[1])

Output:

10	99

Now a and b are two different tables, so changing b does not change a.

Comparing tables

== on two tables checks if they are the same table, not if they have the same values:

local a = {10, 20}
local b = {10, 20}
local c = a
print(a == b, a == c)

Output:

false	true

a and b have the same values, but they are two different tables, so a == b is false. c is another name for a, so a == c is true.

In the exercise, complete a function that adds bonus points to a player table.