OOP: Partly overriding inherited class method

Let’s say we have base class with same method TypeSomething():

function SubClass:TypeSomething()
  base:TypeSomething()
  print("Another message")
end

How to make something like this, so I can override inherited method with still leaving stuff of base function before

1 Like

This is an interesting question, and I like it. Can you show me how you would implement your inheritance here?

local BaseClass = {}
BaseClass.__index = BaseClass

function BaseClass.new()
    local self = setmetatable{{}, BaseClass}
    return self
end

function BaseClass:Inherited()
    print("Hello")
end

local SubClass = {}
SubClass.__index = SubClass
setmetatable(SubClass, BaseClass) -- first inheritance part

function SubClass.new()
    local self = setmetatable(BaseClass.new(), SubClass) -- second inheritance part (instead of blank table using object of base class)
    self.MessageAddedByChild = "World"
    return self
end

function SubClass:Inherited() -- overriding inherited function
    self:Inherited() -- attempt to do what do I want
    print(self.MessageAddedByChild)
end

basicly it’s just getting inf loop, so I need to call function from base class OBJECT but still override it by my own function with same name

I found how to fix it, basicly you just need to get base method in some variable, and then just use that inside of our overriding method. Very easy

local BaseClass = {}
BaseClass.__index = BaseClass

function BaseClass.new()
	local self = setmetatable({}, BaseClass)
	
	function self:Inherited()
		print("Hello")
	end
	
	return self
end

local SubClass = {}
SubClass.__index = SubClass
setmetatable(SubClass, BaseClass)

function SubClass.new()
	local self = setmetatable(BaseClass.new(), SubClass)
	self.MessageAddedByChild = "World"
	local baseInheritedMethod = self.Inherited
	
	function self:Inherited()
		baseInheritedMethod()
		print(self.MessageAddedByChild)
	end
	
	return self
end

local subClassObject = SubClass.new()
subClassObject:Inherited()

-- Output:
-- Hello
-- World

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