今天主要是做个记录,用到了lua中的深拷贝方法,后面用到方便查找
-- 深拷贝函数
local function deepCopy(orig)
-- 检查类型,如果不是表直接返回值
if type(orig) ~= "table" then
return orig
end
-- 用于记录已复制的表,防止循环引用
local origToCopy = {}
local function recursiveCopy(origTable)
-- 如果已拷贝过,直接返回拷贝结果,防止循环引用
if origToCopy[origTable] then
return origToCopy[origTable]
end
local newTable = {}
origToCopy[origTable] = newTable -- 记录已经拷贝的表
for key, value in pairs(origTable) do
if type(value) == "table" then
newTable[key] = recursiveCopy(value) -- 递归拷贝子表
else
newTable[key] = value -- 直接拷贝值
end
end
return newTable
end
return recursiveCopy(orig)
end
-- 使用示例
local originalTable = {
a = 1,
b = {2, 3},
c = {d = 4, e = {5, 6}},
}
local copiedTable = deepCopy(originalTable)
-- 修改原始表内容,检查是否影响拷贝的表
originalTable.b[1] = 100
print(copiedTable.b[1]) -- 输出 2,表明拷贝的是深拷贝