Lua点滴LuaLua脚本语言开发

lua table深拷贝

2018-02-26  本文已影响41人  90d81be3ec65

一、先上代码:

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



二、该函数知识点
1、table也可以作为table的key
2、对于重复出现的table存储在lookup_table中,不必重复拷贝
3、设置新表的原表为被拷贝表的原表
4、对于递归的操作,递归到最后一层务必有返回值

上一篇 下一篇

猜你喜欢

热点阅读