function table.deepcopy(object)
-- 已经复制过的table,key为复制源table,value为复制后的table
-- 为了防止table中的某个属性为自身时出现死循环
-- 避免本该是同一个table的属性,在复制时变成2个不同的table(内容同,但是地址关系和原来的不一样了)
local filter_table={}
local function _copy(object)
if type(object)~="table" then
return object
elseif filter_table[object] then--如果已经拷贝过了,取拷贝过的
return filter_table[object]
end
local new_table={}
for k, v in pairs(object) do
new_table[_copy(k)]=_copy(v) --对键 值 进行拷贝
end
filter_table[object]=new_table --緩存起來
-- 这里直接拿mt来用是因为一般对table操作不会很粗暴的修改mt的相关内容
return setmetatable(new_table,getmetatable(object))--元表也 一起拷貝
end
return _copy(object)
end
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交