How to create a variable with a table and doesn't share the table with another variable?

My problem here is quite straight forward: when I create a variable with an empty table, and then create another variable that equals to that of the previous variable, the table is shared between the two variables.

local A = {}
local B = A

print(A)
print(B)

table.insert(A,"a")

print(A)
print(B)

Both variables A and B appear to have “a” inserted into them, even though “a” was only inserted to table A. Is there a way I can prevent it from doing this?

When you do local B = A it doesn’t create a copy of table “A” and assign it to “B”, but rather only stores the reference to table “A” in variable “B”. Basically “A” and “B” both point to the same table.

This is the same way instances work, e.g.:

local A = Instance.new("Part")
local B = A

“B” isn’t a copy of BasePart “A”, but rather a reference to it, and any changes you apply to “B” will also apply to “A”

If you want to create two separate tables, you would just do

local A = {}
local B = {}

And if table “A” had some data in it and you wanted to clone it as a new table into “B” you could make a shallow/deep copy function that would copy all values from table A into table B

2 Likes