I want to make a OOP system(I am very new to oop) but if I want to slightly extend a function like after the object does it’s attack function it explodes?
Unit Class
local Unit = {}
Unit.__index = Unit
function Unit.new(team, model, position)
local self = setmetatable({}, Unit)
self.Team = team
self.Model = model:Clone()
self.Model.PrimaryPart.Position = position
return self
end
function Unit:Attack()
--attack
print("Attack")
end
return Unit
ExplodingUnit Class
local Unit = require(script.Parent.Unit)
local ExplodingUnit = setmetatable({}, {__index = Unit})
ExplodingUnit.__index = ExplodingUnit
function ExplodingUnit.new(team, model, position, bomb)
local self = setmetatable(Unit.new(team, model, position), ExplodingUnit)
self.Bomb = bomb
return self
end
function ExplodingUnit:Attack()
Unit:Attack()
--Explode?
print("Explode")
end
return ExplodingUnit
How would I get the ExplodingUnit:Attack to run Unit:Attack first?
I’ve heard that you can’t inherit functions in roblox lua?
It’s not entirely clear what you’re trying to do, but if the goal is to extend a class by adding functionality to one of its methods, you can do something like this: local Unit = {}
Unit.__index = Unit
function Unit.new(team, model, position)
local self = setmetatable({}, Unit)
self.Team = team
self.Model = model:Clone()
self.Model.PrimaryPart.Position = position
return self
end
function Unit:Attack()
–attack
print(“Attack”)
end
local ExplodingUnit = setmetatable({}, {__index = Unit})
ExplodingUnit.__index = ExplodingUnit
function ExplodingUnit.new(team, model, position, bomb)
local self = setmetatable(Unit.new(team, model, position), ExplodingUnit)
self.Bomb = bomb
return self
end
function ExplodingUnit:Attack()
Unit.Attack(self) – Call the original method
–Explode?
print(“Explode”)
– Note: calling self:Attack() here will result in infinite recursion
end
Now you can override ExplodingUnit:Attack and still call the original implementation if you want to.
Note that if you want to do this for multiple methods, you can finish the ExplodingUnit definition with code that looks like this: local methods = { “Attack” }
for _, method in next, methods do
local original = ExplodingUnit[method]
ExplodingUnit[method] = function(self, …)
original(self, …)
end
end