Need help with connecting 2 metatables to a parent table (OOP)

I am having issue with connecting two different tables as metatables to my main table. I am pretty new to OOP and I still struggle a bit.

I have the main table in top-hierarchy module which creates me the self table and assigns the generic table (basically containing all the baseline methods) to it like this
image

this works fine and works perfectly, however a bit later on, I assign another table to it containing some specific methods for this type of object, in the same manner

image

however this seems to somehow “disconnect” my original generic table and replace it only with this specific one. Which is an issue.

I have tried looking for solutions, but the only thing I found was this code

local function assignMetatables(masterTable, ...)     
    local metatables = {...}     
    for _, mt in ipairs(metatables) do
         setmetatable(masterTable, {__index = mt})     
    end 
end

which is essentially what I am already doing, which makes me even more confused.

Any help will be appreaciated!

(please do not link me any OOP tutorials, I read most of them but I still struggle)

setmetatable() will overwrite any previous metatables assigned to the object. You could try using the getmetatable() method, and maybe assign __index as a function. This way, you could gather both metatables and have a custom way to find the items within them.

--assigning the first time
local self: SomeTypeForYourClass = setmetatable({}, {__index = AIGeneric})

--assigning the second time
local current: {any} = getmetatable(self)
local secondMeta: {any} = require(script.CombatModules[self.Class])

--gathering the tables
local gathered: {{any}} = {current, secondMeta}

--now assign __index as a function
--I will create the function outside for simpler readability
--I will also overwrite "self" only within this function to show it referes to the class, although it is not used

function indexNil(self: SomeTypeForYourClass, index: string|number|Instance|(...) -> (...:any?)): any?

    --iterate over both tables and attempt to find this index
    for _: number, metatable: {any} in next, gathered, nil do
        if metatable[index] then --index has been found
            return metatable[index]
        end
    end

    --throwing a custom error related to the table
    error("Desired item within table could not be found")
end

--set the __index metamethod to this function
setmetatable(self, {__index = indexNil})
1 Like

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