[meta] Add table deep copy function.

master
Lorenzo Cogotti 2 years ago
parent 96e03c54a5
commit a2180170ed

@ -35,4 +35,33 @@ function meta.mergetable(to, from)
return to return to
end end
--- Table deep copy.
--
-- Copy table 'obj', cloning any sub-table.
-- Handles cyclic references.
--
-- @tparam table obj object to be copied
-- @tparam[opt={}] table copied known copied sub-object table
-- @treturn table newly created clone of 'obj'
function meta.deepcopy(obj, copied)
copied = copied or {}
local r = {}
copied[obj] = r
for k,v in pairs(obj) do
if type(v) == 'table' then
local t = copied[v] or meta.deepcopy(v, copied)
copied[v] = t -- NOP if object was already copied
v = t
end
r[k] = v
end
return r
end
return meta return meta

Loading…
Cancel
Save