LuaTable 深拷贝
在近期工作中有需要用到深拷贝,用作记录
local function DeepCopy(tab, stackAddr)
local result = {}
if not stackAddr then
stackAddr = {}
end
stackAddr[tostring(tab)] = result
local tempAddr
for key, value in pairs(tab) do
if type(value) == "table" then
for key1, value1 in pairs(stackAddr) do
if key1 == tostring(value) then
tempAddr = key1
end
end
if tempAddr then
result[key] = stackAddr[tempAddr]
else
result[key] = DeepCopy(value, stackAddr)
end
if getmetatable(value) then
result[key] = setmetatable(result[key], getmetatable(value))
end
else
result[key] = value
end
end
return result
end
其中stackAddr在实际调用时不需要传入,仅作为递归时检查有无循环引用