Metatables question

Soo today when working with OOP i observed very strange behavior, it happens when we have nested metatable, for instance:

Class Creator → Class → Object

Note: Class Creator is module that creates classes and have some shared methoods like constructor or metatables

When it happens

The strange thing happens when you try to call methamethood inside Class Creator from Object, if we write:

print(Object.SomeIndex) 

If there is __index methamethood inside Class Creator it will fire normally, but let say we have __add metamethood inside Class Creator and we call it from Object

print(Object + {1, 2, 3})

It will throw an error, as if metamethood won’t fire

Note: Class have table cycle reference, soo object inherits all of class’s methoods, when class’s metatable is Class Creator

Question is, if __index metamethood is recursive, this mean if let’s say Object don’t find index, it searches through Class, but if Class have metatable, it searches through it too?

Ok soo i made few tests, and it turns out that __index is recursive as long as there is table cycle reference

local mt = {
    __index = function()
        return "hi"
    end,
}

local mt2 = {
    B = "y"
}
mt2.__index = mt2 -- reference 2
setmetatable(mt2, mt)

local mt3 = {
}
mt3.__index = mt3 -- reference 1
setmetatable(mt3, mt2)

local t = setmetatable({}, mt3)
print(t.A)

Soo what happens is that if table A doesn’t find index, it searches through it’s metatable, but metatable have cycle reference, soo it returns metatable, but inside metatable we have another metatable, soo it repeats this until there is no more __index

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.