Could someone explain me .index in OOP?

I’ve been interested in OOP recently but don’t understand all the features. Looking through some guides I found that most of them were using something like: Variable._index = Variable What does this set or mean?

.__index runs only if it is the metatable of another table.
For example:

local testTable = {}
local meta = {testVal = "hi"}
meta.__index = meta

This is usually how you see .__index. It is supposed to be a function, but you can set it to a table.
How this works is that if you try to index something in the table and it isn’t there, it looks inside of .__index.

setmetatable(testTable, meta)
print(testTable.testVal) --> "hi"
1 Like

The “__index” metatable key is used in Lua OOP to support inheritance. It’s accessed whenever you try to read from a table using a key that does not exist, and the table has a metatable with the key “__index”. The value stored for this special key can be a function or a table.

In the most common Lua OOP pattern, the base class is its own metatable, and derived class’s metatable extends the base class metatable. If you try to call derivedClass.foo(), and the derived class has no method named “foo”, it triggers the interpreter to look at the derived classes’s metatable “__index” entry, for the base class function “foo”. This way, OOP works like in other languages, where derived classes automatically inherit their parent class’s members unless they explicitly define their own to override them.

There is a very thorough explanation here: Learning Lua - Referenced Values, Metatables, and Simple Inheritance

3 Likes