Metatable Problem

So, I know that lua will look at the table metatetable if it does not contain a reference to the variable I, but it seems wrong that when I try to set a variable that does not exist in the table, it sets it to a metatet instead.

Here is an example of what I mean

a = {__index = {tbl1 = {var = 1}, tbl2 = {var = 2}}}
b = setmetatable({}, a)
print(b.tbl1.var, a.__index.tbl1.var)
b.tbl1.var = 2
print(b.tbl1.var, a.__index.tbl1.var)

In this code, it will replace the metatables variable instead of setting it in the im table that references it.

However, this does not happen with this code.

a = {__index = {4, 5, 6}}
b = setmetatable({}, a)
print(b[1], a.__index[1])
b[1] = 2
print(b[1], a.__index[1])

Does it require more work when using metadata and nested tables? Or is there a way around this?

+4
source share
1 answer

In this code, it will replace the metatables variable instead of setting it in the im table that references it.

, ; tbl1 , . , , , . b = setmetatable({tbl1 = {}}, a), , .

? ?

, . Lua autovivification, tbl.foo = 1 tbl, . tbl1 , , . , , , .

0
source

All Articles