how is a function navigating through fields of a table

Viewed 34

i already asked this question on stackoverflow and accepted an answer i think i did not really understand the answer and i got some more question, im embarrassed to necro it so im creating a new question

im learning lua and got to metatable part, in this example

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)

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 so print(f+t) looks like print(super+super) how does tb.add(super,super) find the fields of super table using return s1.s..s2.s also as the tb.new function is called twice and setmetatable(super,meta) happens twice is there any difference between the first and second iteration? if any of the above are incorrect please correct me.

1 Answers

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

No. It's more like super['s'] = 'W'. That's how dot notation works. I hope that clarifies how Lua "finds the fields" later.

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

They're different, because the super variable is a new table each time. Any time you see {} (a table constructor), whether empty or not, it's creating an entirely new table. meta, however, is still the same table, because it only gets a table constructor once, outside of any function.

Related