[meta] Add table deep copy function.

This commit is contained in:
Lorenzo Cogotti 2022-09-01 08:27:39 +02:00
parent 96e03c54a5
commit a2180170ed
1 changed files with 29 additions and 0 deletions

View File

@ -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