lua实现深度拷贝table表

lua当变量做为函数的参数进行传递时,相似的也是boolean,string,number类型的变量进行值传递。而table,function,userdata类型的变量进行引用传递。故而当table进行赋值操做之时,table A函数

赋值给table B,对表B中元素进行操做天然也会对A产生影响,固然对B表自己进行处理例如B =nil或者将表B指向另外一个表,则对A是没什么影响的;下面便是对lua table的深度拷贝。lua

 

deepcopy = function(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 index, value in pairs(object) do
            new_table[_copy(index)] = _copy(value)
        end
        return setmetatable(new_table, getmetatable(object))
    end

    return _copy(object)
end

local testA =  {1,2,3,4,5}

local testB = testA
testB[2] = "我擦"

local testC = deepcopy(testA)
testC[2] = "我勒个去"

for k , v  in ipairs (testA) do
    print("testA",k, v )
end

print("============================")

for k , v  in ipairs (testC) do
    print("testC",k, v )
end

运行结果以下:spa

testA 1 1
testA 2 我擦
testA 3 3
testA 4 4
testA 5 5
============================
testC 1 1
testC 2 我勒个去
testC 3 3
testC 4 4
testC 5 5code

相关文章
相关标签/搜索