Question about metamethod __index

I understand metamethods fairly well. I can use them if I need to. There is one thing I have always seen and have never understood the purpose of. Certain module scripts I have come across have looked like this:

local moudle = {}
module.__index = module

return module

I understand everything about this, except line 2. Why would you even bother including that line of code? Doesn’t it just make the table search itself, which it is already doing by default? Any help is appreciated, thanks.

Fires when table[index] is indexed, if table[index] is nil. Can also be set to a table, in which case that table will be indexed.
Metatables | Roblox Creator Documentation

Being new to OOP and metamethods, I’m only making assumptions here. But when using OOP you have tables which will have their metatable set to the module in this case. Now because of how OOP works you are telling this new table to get methods it doesn’t have (which means this table indexed something which is nil) so it goes to it’s metatable for the index. And because this index returned nil it then prompts .__index to fire and use the table provided to index for the function.

So yes, it’s making the table search itself, but it’s due to a certain condition that was met which is common in OOP.

From a logistics perspective, this concept still makes no sense to me. Your making the table look through itself, which it is already doing anyways. Does __index do something else under the hood of roblox’s engine that I am not aware of?

this is used to do OOP in lua. More precisely it is a small optimization.

1 Like

Actually not, it makes the table with the metatable set search the metatable table instead of searching itself.

This is usually for oop stuff as @xZylter mentions. Usually you have a table of properties and one single shared metatable containing all the functions that does stuff with those properties.

Here is it’s equivalent code piece example for the function inputted into the index function.

2 Likes