Lua metamethods are not called

I'm a little new to Lua (I haven't really done much with it), and I'm trying to ponder the meta tags. I worked on them before, but now (after a few months) I came across something really strange.

What should i do when printing a script at startup?

__mt = {}

__mt.__index = function(table, key)
    print("In __index")
    return 99
end

test = {}
test.x = 5

setmetatable(test, __mt)

print(test.x)

Personally, I expect it to print "In __index" (from the metamethod), followed by 99. However, whenever I run it, I get 5. Nothing that I do can make the index metamethod work. It just acts like I'm using rawget().

Curious by adding

print(getmetatable(test).__index(test, "x"))

will do the right thing. There is a metatet that is __index()correct; it just is not called.

Is this a mistake or am I just doing something stupid? I can not tell.

+3
1

( , ), __index, , x t.x. print(t.y)!

: , -.

function doubletable(T)
  local store = T or {}
  local mt = {}
  mt.__index = function (t, k) return store[k] and 2*store[k] end
  mt.__newindex = store
  return setmetatable({}, mt)
end

t = doubletable({a=1, b=3})
t.c = 7
print(t.a, t.b, t.c)
-- output: 2    6   14
+8

Source: https://habr.com/ru/post/1751838/


All Articles