Skip to content

Instantly share code, notes, and snippets.

@cloudwu
Created October 12, 2016 07:21
Show Gist options
  • Save cloudwu/9a45d1c1854cf01120dbf24878d764c4 to your computer and use it in GitHub Desktop.
Save cloudwu/9a45d1c1854cf01120dbf24878d764c4 to your computer and use it in GitHub Desktop.
deep copy lua table
-- deepcopy a lua table, no recursion sub table, the key never be a table.
local function _copy(obj, target)
local n = 0
-- clear target table
for k,v in pairs(target) do
if type(v) == "table" then
v.__del = true
n = n + 1
else
target[k] = nil
end
end
-- copy obj into target
for k,v in pairs(obj) do
if type(v) == "table" then
local t = target[k]
if t then
t.__del = nil
n = n - 1
else
t = {}
target[k] = t
end
_copy(v, t)
else
target[k] = v
end
end
-- clear no use sub table in target
if n > 0 then
for k,v in pairs(target) do
if type(v) == "table" and v.__del then
target[k] = nil
end
end
end
end
local function deepcopy(obj, target)
target = target or {}
_copy(obj, target)
return target
end
------ test ---------
local print_r = require "print_r"
a = { a=1, b=2 , c = {} }
print_r(a)
local b = deepcopy(a, { d = 3, c = { a = 1} } )
print "---------------------------"
print_r(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment