lua实现深度拷贝table表

时间:2023-12-23 17:13:55

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 = {,,,,} local testB = testA
testB[] = "我擦" local testC = deepcopy(testA)
testC[] = "我勒个去" 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