__index Metamethod Explanation
The __index
metamethod is useful for classes, as whenever you want to create a new class it could index it to the metatable.
That might be confusing, but to explain it in more detail here is an example with a table using the __index
metamethod.
Let’s say we create a new metatable and a table, as you can see in the example below using the __index
metamethod.
local metatable = {x = 1}
local normalTable = {}
metatable.__index = metatable
setmetatable(normalTable, metatable)
Now as you can see if we try to print out the x from the normalTable
it would usually print nil
, but as you can see we have a metamethod, different metamethods have different uses.
print(normalTable.x)
When we print out x, it will index it and grab it from the metatable
.
What is indexing?
Indexing is essentially when you access something or get something for example
normalTable.x
or
normalTable["x"]
So the __index
metamethod is essentially just grabbing something from your metatable here is another example if you don’t understand.
Metatable
You: Hey can you give me “x”?
Normal Table: Sorry, I don’t have an “x”.
Normal Table: asks metatable if he has an x and if he does give it to him
Meta Table: Sure I have “x”, here you go.
Normal Table: gives you “x”
No Metatable
You: Hey can you give me “x”
Normal Table: Sorry, I don’t have an “x”
Classes
So now why do set the __index
metamethod to itself?
Well, you essentially set the __index
metamethod to itself because when you set it to the metatable it will know to index it to itself.
Example
Here we have a class, and it sets it’s __index
metamethod to itself.
local class = {}
class.__index = class
function class.new()
local self = {}
setmetatable(self, class)
return self
end
function class:doSomething()
end
return class
Why does it do this?
Well because class
is a essentially just a variable with a table and it stores all of the methods, methods are functions that pass itself first as an argument.
They are contained within the class and if you have just created a new class, you can’t access them without indexing it as it would be empty.
So as you can index it the normal class will return the method.
That is why you use the __index
metamethod.