Lua-深拷贝
--- 深拷贝对象 -- @param srcObj 对象 local function deepCopy(srcObj) --- 已被拷贝的对象列表(解决循环引用的问题) local lookup = { } local function _copy(object) if type(object) ~= "table" then return object elseif lookup[object] then return lookup[object] end local newTable = { } lookup[object] = newTable for k, v in pairs(object) do newTable[_copy(k)] = _copy(v) end return setmetatable(newTable, getmetatable(object)) end return _copy(srcObj) end
cocos2d 提供了一份
function clone(object) local lookup_table = {} local function _copy(object) if type(object) ~= "table" then return object elseif lookup_table[object] then return lookup_table[object] end local new_table = {} lookup_table[object] = new_table for key, value in pairs(object) do new_table[_copy(key)] = _copy(value) end return setmetatable(new_table, getmetatable(object)) end return _copy(object) end