Alternate solution for inheritance

So basically I have this class that wants to use the methods on a different class, for what reason is that it depends on the parent’s class. Just for simplicity this is what the setup currently looks like:

local Class = {}
function Class:__index(index: string)
	return Class[index] or self.__methods[index]
end

function Class.new(object: Instance)
	local self = setmetatable({
		object = object
	}, Class)

	if object:FindFirstAncestorWhichIsA(otherClass1) then
		self.__methods = OtherClass1
	elseif object:FindFirstAncestorWhichIsA(otherClass2) then
		self.__methods = OtherClass2
	end

	return self
end

return Class

You should reverse the inheritance. Make Class the base class that has shared functions between OtherClass1 and OtherClass2, and then those two classes would have Class as the parent class.
For example:

local Class = {}
Class.__index = Class
function Class.new(object: Instance)
    return setmetatable({
        object = object
    }, Class)
end

local OtherClass = {}
OtherClass.__index = OtherClass
setmetatable(OtherClass, {
    __index = Class -- inherit methods from Class
})
function OtherClass.new(object: ClassName)
    local self = Class.new(object)
    setmetatable(self, OtherClass) -- Overwrite the metatable, but keep the original table with properties
    return self
end
1 Like

I see. I was about to mention that my method was not going to work because I was not using or setting the properties of OtherClassN. But the main reason why I was doing the other way around was to adjust depending on the parent’s class, the same thing that Instance is doing.

Nvm, all I needed was to set the metatable of the OtherClassN inside of Class; what I was doing was requiring the Class inside the OtherClassN, which led me to my first solution.

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