lua实现深度拷贝table表


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

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

 

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

运行结果如下:

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 5


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM