函数如何在 table 的字段中导航

how is a function navigating through fields of a table

我已经在 Whosebug 上问过这个问题并接受了一个答案我想我并没有真正理解这个答案而且我还有一些问题,我不好意思把它弄死所以我创建了一个新问题

我正在学习 lua 并进入元table 部分,在这个例子中

local tb = {}
local meta = {}

function tb.new(s)
local super = {}
super.s = s

setmetatable(super,meta)

return super
end

function tb.add(s1,s2)

return s1.s..s2.s

end

meta.__add = tb.add

f= tb.new("W")
t= tb.new("E")


print(f+t)

当编译器到达f = tb.new("W") 我认为这会发生 function tb.new("W") super.W = W return setmetatable(super,meta) return super end 所以 print(f+t) 看起来像 print(super+super) 如何 tb.add(super,super) 使用查找 super table 的字段 return s1.s..s2.s 也作为 tb.new 函数被调用两次并且 setmetatable(super,meta) 发生两次第一次和第二次迭代之间有什么区别吗?以上如有不妥请指正

when compiler gets tof = tb.new("W") i think this happens function tb.new("W") super.W = W return setmetatable(super,meta) return super end

没有。它更像是 super['s'] = 'W'。这就是点符号的工作原理。我希望这能阐明 Lua 稍后如何“找到字段”。

as the tb.new function is called twice and setmetatable(super,meta) happens twice is there any difference between the first and second iteration?

它们是不同的,因为 super 变量每次都是一个新的 table。任何时候你看到 {}(一个 table 构造函数 ),无论是否为空,它都在创建一个全新的 table。然而,meta 仍然是相同的 table,因为它只在任何函数之外获得一次 table 构造函数。