LUA QUESTION: Why changing a key from a table that was set as another table changes both?

Why changing a key from a table that was set as another table changes both?

The title is confusing, so, let me show a example:

Code:

ATable = {
     4,
     "A String Lmao"
}

AnotherTable = ATable

AnotherTable[2] = "This is a different string!"

print(ATable[2])

Output

"This is a different string!"

Why does this happen, i never actually changed “ATable”, is there a behaviour of tables i’m missing?

1 Like

Tables are passed by reference, so the same table in memory is pointed to by both variables. This is unlike, for example, numbers, which are passed by value.

Notice that if you print both table variables, they have the same hash.

1 Like

They are the same table. Assignment of tables is by reference, a copy is not made. It is the same for “objects”; if you have part = Instance.new("Part") and part2 = part, they are the same part.

so @colbert2677 and @1waffle1, i would need to manually copy over every key of “Atable” to “AnotherTable”?

You would. This often involves iterating through the table and taking key-value pairs from the first table and placing them into a second. The Lua-Users Wiki has some good implementations for copying tables:

http://lua-users.org/wiki/CopyTable

1 Like

so, something like this would do?

for i = 1, #Settings do
     TemporarySettings[i] = Settings[i]
end

There are some other options to use a table as a template or such that don’t require you to actually copy it. For example, you can create a ModuleScript of the table and just require that when you need one. It would be useful to have a deepcopy function on hand though.

1 Like

That would only cover indices with numerical values, so no. I’d use pairs with an arbitrary key.

for key, value in pairs(Settings) do
    TemporarySettings[key] = Vaue
end
1 Like

Strings are also passed by reference.

local a,b = “test”,“test”
These are both the same value internally.

1 Like

That’s right, I forgot. And string functions take the string and produce a new one with the changes applied to them. Removed the string mention from my post.

1 Like

Same with concatenation.


WORDS

1 Like