DEV Community

Oggetto
Oggetto

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay