I am studying object oriented programming with Lua. I am having trouble understanding the functional differences between assigning a table in the __index field of an instance and setting a metatable for the instance. I reviewed the official Lua's reference manual, but I dont fully grasp the difference. For example, to create an instance of the Account class, it sets the __index field of the Account class (self) to itself, then sets the instance's metatable to the Account class.
function Account:new (o)
o = o or {}
self.__index = self
setmetatable(o, self)
return o
end
What is going on here? In this case, why is Account setting it's own index to itself? What's the use of true metatables in this case if the instance 'o' is just using the Account class as its metatable? Why does Lua allow classes be metatables for its instances?
From my understanding, metatables are supposed to be tables comprised only of metamethods (__newindex, __index, __add, etc.). But the example has __index as a field of the Account class, which by this point, is not a metatable and doesn't have a metatable assigned to it such that the assignment looks up another metatable, if that makes sense.
Thanks in advance.