DEV Community

JustOptimize
JustOptimize

Posted on

Tables SUCK and this is WHY

Hi everyone after a WEEK of debugging code I found out that assigning a table to a variable in lua, js, ruby and many other languages creates a reference to the original table instead of creating a copy.

This means that every time you edit the new variable it actually edits the original table.

How can I create a copy? (Lua)

To actually create a copy you need to do this:

local myTable = {}
for k, v in pairs(myOtherTable) do
    myTable [k] = v
end
Enter fullscreen mode Exit fullscreen mode

PS: Please note that this will create shallow copies, which means only the top-level elements will be copied. If the original table contains nested tables (subtables), those subtables will still be referenced by both the original and the copied table.

In my case

This occurs even when saving a subtable so even with something like local myTable = myOtherTable[a][b] will reference the table and not copy it

REMEMBER THIS, don't be like me and spend more than 10 hours on something as stupid as this.

Top comments (0)