为什么覆盖对象参数不会将新引用传递给外部范围?

Why overwriting an object argument does not pass the new reference to outside scope?

我对 Lua 如何处理函数参数中的对象引用感到有点困惑。考虑这个例子:

local tableA = {name = "A"}
local tableB = {name = "B"}
local tableC = {name = "C"}

local function childA(a, b)
    a = tableC
    b.name = "This works"
end

local function childB(a, b)
    print("a =", a.name) -- expected to print "C"
    print("b =", b.name) -- prints "This works" as expected
end

local function parentFunction(a, b)
    childA(a, b)
    childB(a, b)
end

parentFunction(tableA, tableB)

我希望在 childA 函数中,a 参数将被替换为对 tableC 的引用,从现在开始将继续为 tableC,但是它不会发生。而如果我在 b 参数中仅更改此类参数的 属性,它将影响对对象的读取。为什么覆盖不能像这样工作?

Table 值是通过引用而不是值来复制的。

childA 中,您将 tableC 分配给 aachildA.

本地

a = tableC 只是添加了对 table tableC 的第二个引用。 这对实际 table 和任何其他引用都没有影响。

childA 返回后,a 超出范围,因此您刚刚添加的引用将被删除。

确保您了解在 local tableA = {name = "A"} 中您使用 table 构造器 {} 和对该 tableA 的本地引用创建了一个 table 值=40=]值。 local a = tableA 只是创建另一个对 table 的引用,而不是第二个 table!然后 a = tableCa 重新引用到此处创建的 table local tableC = {name = "C"}

你基本上是在一张纸上写下另一个地址。这不影响原地址的房子。