Lua 5.3.5 中 table.insert 的意外行为

使用table.insert(...)时如下所示:

test ={}
table.insert(test, 1)
print(test[1]) -- 1

table.insert(test, 2)
print(test[1]) -- 1

预期的打印结果是

1

1

现在当你这样做:

local A = { b = {} }
local B = { c = { x=0 } }

function add(t, X)
  local temp = B
  temp.c = {x=X}
  table.insert(t.b, temp)
end

local a = A
add(a, 1)
print(a.b[1].c.x) -- 1

add(a, 2)
print(a.b[1].c.x) -- 2

结果是

1

2

但是它不应该也是1和1吗?这是我的预期行为,因为我两次都访问了_inner_表b的第一个元素。我在这里错过了什么吗?

点赞
用户1442917
用户1442917

我并不完全理解你在代码中想做什么,但你得到了 2 而不是你期望的 1,因为第一个和第二个元素指向同一个表,所以你认为只应用于第二个元素的修改实际上是应用于两个元素的(因为你的 local temp = B 赋值,使得 B 在每个插入的元素中使用)。

在你的脚本末尾添加 print(a.b[1] == a.b[2]) 来确认。

2018-09-08 01:07:44
用户1511417
用户1511417

问题在于 Lua 不通过值来复制表格。您需要使用深层复制机制来复制表格中的所有内容。这里的代码提供了所需的 "A" 和 "B" 的默认值,并且像预期的那样工作。

function init_A(B)
    local t = {}
    if not (B== nil) then
        t.b = B
    else
        t.b = {}
    end
    return t
end

function init_B(C)
    local t = {}
    if not (C== nil) then
        t.c = C
    else
        t.c = { x=0 }
    end
    return t
end

function add(t, X)
  local temp = init_B({x=X})
  table.insert(t.b, temp)
end

local a = init_A()
add(a, 1)
print(a.b[1].c.x) -- 1

add(a, 2)
print(a.b[1].c.x) -- 1
print(a.b[2].c.x) -- 2
2018-09-08 10:31:40