Lua Table 的引用,踩坑记

Lua Table 引用

引用示例

local m = {
    foo = 'bar'
}

local test = m

m.foo = 'foo'

print(test.foo) -- output: foo

由于 lua 对 table 的设计,赋值都是指针型赋值的从而导致了这个问题,这种做法在存储上是有优势的,我们这里只对本身需要深拷贝的 table 进行处理

解决办法

官方推荐的做法

function deepcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in next, orig, nil do
            copy[deepcopy(orig_key)] = deepcopy(orig_value)
        end
        setmetatable(copy, deepcopy(getmetatable(orig)))
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end
点赞