r/lua • u/myclykaon • Aug 17 '25
setmetatable and __index
I'm doing more on classes - and I'm making a class
MyClass = {}
function MyClass:new()
o = {}
setmetatable(o, MyClass)
self.__index = MyClass
return o
end
function MyClass:myfunc()
print("myfunc called")
end
c = MyClass:new()
I realise the manual example uses 'self' rather than MyClass - but I'm not looking for inheritance yet.
And I'm wondering why I need both to set the metatable and __index to MyClass. Just setting the metatable fills the metatable of c with fields named after the MyClass functions (eg myfunc) that point to the metamethods - so they should be callable? Yet calling them is calling nil. Why do I require __index to be set as well? I've read the manual on the __index metamethod and I see how setting __index to the MyClass table and the __index metamethod is called if there is no field in the metatable - yet the metatable of c has the field myfunc in even if I miss setting __index.
1
u/myclykaon Aug 18 '25
Thanks all for the comprehensive explanations and corrections!
5
u/Civil-Appeal5219 Aug 17 '25
Metatables don't work the way you think they do. They tell the Lua runtime "here's how I want you to handle these behaviors for this table". For instance, if you have a table foo and you do foo + 5, Lua will look for a "_add" method on the metatable for foo and call it if it exists (like a getmetatable(foo)._add(foo, 5))
One of the behaviors you can customize is "what do you do if I try to access a property on the metatable and it doesn't exist?". You do that by setting _index on the metatable to either a table or a function.
For your case, it just happens that, if the property you're trying to access doesn't exist, you want Lua to look in the metatable.
2
u/[deleted] Aug 18 '25 edited Aug 18 '25
You have an improper implementation of self, I have provided a proper implementation below. I will now explain the implementation I have used many times. It's very hard to understand but I gave you something to tinker with.
Here's the line by line explanation for the code block below
2
u/Calaverd Aug 18 '25
When we are doing
setmetatablewith another table that contains a__indexfield, what we are telling Lua is that when it fails to find an index in the table, it should look for it in the table referenced as__index.So doing this:
What is happening at our back, is that using the call with a ":" instead of a "." is telling lua, "You will take this table, and use it as first arg for the function that is following next" . So it is equal to doing this (notice how the self arg has been declared explicitly):
At the end of the day is just a way to cheat class functionality into lua using syntactic sugar :)
1
u/DrSeafood Aug 18 '25 edited Aug 18 '25
You’ve got a lot of great answers here; just chipping in with mine …
Example:
If I print A.greeting, nothing happens, since A is missing a “greeting” field. When a table has a missing field, metatables help us make a backup plan:
This means, “If A is missing a field, check B instead.” So now if you type print(A.greeting), you’ll get “hello” because it looks up B’s greeting as a backup plan.
In your class constructor: the line
makes it so we can inherit from X. Eg later if I make a new object called Y, I could set Y’s metatable to X, and then any missing fields in Y will be looked up in X.__index — which is MyClass. instead. And if MyClass still doesn’t have that field, it will go one more and check the parent class, etc.
1
u/nadmaximus Aug 18 '25
This cheatsheet is what I have bookmarked for reminding myself about metatable methods.
1
u/Own-Alternative3291 Aug 18 '25 edited Aug 18 '25
Metatables are tables because that's the only data structure the lua has that allows to store multiple metamethods. In that case, why not just use the table that you're trying to index from instead of creating a new one each time?
In your example, assuming you do
Your 'self' is MyClass itself, so you're basically doing this
And your function can be simplified into
You can use both 'self' and MyClass, the difference is 'self' is always gonna be the table you're trying to call from.