Math Is Fun Forum

Discussion about math, puzzles, games and fun.   Useful symbols: ÷ × ½ √ ∞ ≠ ≤ ≥ ≈ ⇒ ± ∈ Δ θ ∴ ∑ ∫  π  -¹ ² ³ °

You are not logged in.

#1 2021-05-22 01:28:39

Xuer
Member
Registered: 2019-12-23
Posts: 4

LUA how is a function navigating through fields of a table

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 posting it here

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

return s1.s..s2.s

end

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

print(f+t)``````

when compiler gets to

`` f = tb.new("W") ``

i think this happens

`` function tb.new("W")  super.W = W return super end ``

so

``print(f+t) ``

looks like

``print(super+super) ``

how does

`` tb.add(s1,s1) ``

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.

Last edited by Xuer (2021-05-23 03:35:24)

Offline

#2 2021-05-25 02:29:35

Xuer
Member
Registered: 2019-12-23
Posts: 4

Re: LUA how is a function navigating through fields of a table

i got an answer on another website, so i was under the impression that in this part

``super.s = s``

the parameter passed to the function

``tb.new``

replaces both

``s=s``

turns out it does not and only replaces the rvalue so

`` return s1.s...s2.s``

works because the index of

`` super``

is

``s``

not the value passed to the function  and the table

``super``

is destroyed upon exit of the

``tb.new``

function and when it is called again the table is created again, so there are two different versions of the same table.

Offline