Confirm my understanding of metatables

So I’ve been using OOP with Metatables for a little while here after transitioning from strictly functional programming and basically I have been using it but don’t really understand it fully.

So is my understanding right in that if b calls x and it isn’t there then it checks it’s metatable for a Metamethod and then fires the metamethod in this case __index?

local a = {}
a.__index = a
a.x = 250

local b = setmetatable({}, a)


I’m interested in the responses of this post since I have no clue what a metatable or metamethod is.

1 Like

If you don’t know then you should check out this post All you need to know about Metatables and Metamethods this will explain it.

1 Like

You should read more about that here: Programming in Lua : 13.4.1. You’re basically correct, but your use of terminology is a bit off.

“Calling” is generally only used to talk about “calling functions”. In your example you’re not calling b, you’re “indexing into” b, i.e. looking up the key “x” in the table b.

yes, but

is not quite right. Yes, it looks for “a” metamethod, but specifically it always looks for the __index metamethod, not just “in this case”. No other metamethod has the same effect as the __index metamethod, they have completely different behavior.

“Firing” is something you do to Events, not methods or functions. Again, you call them. In this case it isn’t even called either, since a.__index is a table and not a function. You can set __index to either a table or a function, resulting in in different behavior. If it’s a function, then yes it gets called with the table that has the metatable (b in this case) and the key as parameters. If it’s a table, the result of the lookup is whatever the result would be if you performed the lookup with the same key but on __index. Since __index = a, b.x results in a.x results in 250.

1 Like

Alright thankyou, I get it now that metamethods only get used if the conditions are met when interacting with a table like __index is only used when the table is indexed with nil.