Overriding table when editing cloned version?

When you create a copy of a table, both the original and copied table end up connected. If you make changes to one, it affects the other, basically like twins.

As a solution, you need to create a copy of the table that is independent so it doesn’t affect the other

View code
function cloneTable(original)
    local copy = {}

    for key, value in pairs(original) do
        if type(value) == "table" then
            copy[key] = cloneTable(value)
        else
            copy[key] = value
        end
    end
    return copy
end

local tableTest = {"Hello!", Phrases = {["Good Riddance!"] = false}}
local cloneTable = cloneTable(tableTest)

cloneTable.Phrases["What in the World?"] = true

print("cloneTable:")
for k, v in pairs(cloneTable) do
    print(k, v)
end

print("tableTest:")
for k, v in pairs(tableTest) do
    print(k, v)
end
1 Like