I’m trying to learn OOP but everyone and everything keeps on saying you need to understand metatables first. Could someone explain their purpose?
The purpose of __index (which is used in OOP) is to save memory. A common mistake is to put a function inside of every table that you make, which is horribly inefficient when making many objects.
When a table has a metatable for __index and you reference something that doesn’t exist in the table it will first check the metatable for the missing thing (such as a function) and call that instead if it exists. This saves a ton of memory because there is only one function that every table is calling, instead of each table having it’s own function.
A really nice thing about __index and self is if you call a function through a metatable self will be equal to the table that you are calling the function from instead of the table that stores the function.
Hope this helps!
That helps so much! Thank you. I tended to use the first method that’s less memory efficient and I will definitely switch over to the other one.
I recommend this tutorial it’s really easy and short:
And this tutorial if you want get deeper into OOP and metatables:
That is indeed one of the benefits, but I’d argue the usage of
__index is more of a good design choice, as in it’s the way “resolving which method to call for an object” should be done, just like it’s done in many other languages (although mostly under the hood).
If I call a method of an object,
obj:Method(), which function such a call referred to, is decided at runtime, meaning while the code is running, in the case of lua via
__index. This is referred to as dynamic (meaning “done at runtime”, as opposed to static, meaning done while the code is compiling) dispatching (since it literally dispatches/resolves your call to the proper function).
In a language such as C++, this is done under the hood implicitly via the vtable mechanism for example (wikipedia, although not that it’s a good way to understand the concept, but it’s a good way to get down the rabbit hole due to the many references). But of course in the case of C++, due to its nature of being statically typed, this mechanism is essential (info on that).
Does anyone have an example of when they used Metatables in their game and for what purpose? Because I’m still struggling to figure out why when I should use this.
I wrote multiple in depths articles and I also work for Amazon specializing in that paradigm.