Table shallow copy won't update it´s values

, ,

Hi all!

I've just started tinkering with the SDK, and I´ve found something that made me scratch my head.

When doing a shallow copy of an table of tables, if I update the original values, the copy is updated as expected.

On the other hand, when I shallow copy a "flat" table, and update the original values, the copy is not updated.

Screenshot 2023-01-28 at 00.22.21

In the documentation, it says:

The copy will contain references to any nested tables.

My interpretation is that is contains references to any nested tables, as well as the reference of the actual table, if it was flat. Was that interpretation a mistake? Does it mean -only- nested tables or am I missing something else?

Thank you!

(I´m developing on MAC)

What you have to keep in mind about Lua variables is that you're not dealing with pointers, you're dealing with references. When you run the following code:

local a = "some string"
local b = a

You're not telling b to always point towards a, you're telling it to store whatever the value of a is at that point in time. The value of b becomes "some string" when the assignment is performed and retains that value even when a changes.

Tables are tricky in this regard, in that the following code will cause both variables to reference the same table object in memory:

local a = { } -- let's call this <table:01>
local b = a

a.value = "some string" -- read as: <table:01>.value = "some string"
b.value = "some string" -- read as: <table:01>.value = "some string"

With this in mind, the difference between a deep copy and a shallow copy is that a shallow copy initializes a new table and fills it with the same key=value pairs as the original, pointing to the same objects in memory as the original, whereas a deep copy will look for arbitrarily deeply nested tables and copy the contents of those as well. Think of the result as such:

a = <table:01>{ <table:02>{ "some_value" } }
b = table.shallowcopy(a)  -->> <table:03>{ <table:02> }
c = table.deepcopy(a)      -->> <table:04>{ <table:05>{ "some_value" } }


I was misinterpreting the documentation, as I expected.

Thank you for the explanation!