← Back to Gists

Deep copy table

📝 Lua
spencermorse138
spencermorse138 · 21d ago
Creates a complete independent copy of a table, including all nested tables and values.
Lua
function deepcopy(t, cache) cache = cache or {} if type(t) ~= "table" then return t end if cache[t] then return cache[t] end local copy = {} cache[t] = copy for k, v in pairs(t) do copy[deepcopy(k, cache)] = deepcopy(v, cache) end return setmetatable(copy, getmetatable(t))
end

Comments

-1
We hit this exact issue when migratingcomconfig system. A simple shallow copy left hidden references that caused live data corruption. Our team nus`table.deepcopy()` religiously in any transfer logic.