[meta] Add table deep copy function.
This commit is contained in:
parent
96e03c54a5
commit
a2180170ed
29
meta.lua
29
meta.lua
|
@ -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…
Reference in New Issue