Inheritance with luau oop not inheriting present functions

I aim to inherit the functions from my Hostile class and use them with my Boss class.

Here is a simplified version of my code:

Boss module:

local Boss = {}
Boss.__index = Boss

function Boss.new(class, datatable)
	local newhostile = Hostile.new()
	setmetatable(newhostile, Boss)

	return newhostile
end

function Boss:ManualOverride()
	self.Conditions.HostileDies.Met = function()
		print"BOSS DIED! WIN!"
	end
end



return Boss

Hostile class module:

local Hostile = {}
Hostile.__index = Hostile

function Hostile.new()
	local hostile = {}
	setmetatable(hostile, Hostile)
	
	hostile.States = {}
	hostile.Conditions = {}

	return hostile
end

function Hostile:Spawn(spawnpart)
print"spawned"
end

Core script calling my boss module:

local boss = BossModule.new(bosstype, BossData.Data[bosstype])
boss:Spawn(spawnpart) -- errors, spawn not recognized and is nil
boss:ManualOverride()

Doing this does not allow me to inherit the Spawn function from the Hostile class. This means I can’t call Spawn from my boss object. Can someone explain why? Am I overriding the old metadata? How do people usually go about extending classes correctly?

Change BossModule to this

local Boss = setmetatable({}, Hostile)
Boss.__index = Boss

function Boss.new(class, datatable)
	local newhostile = Hostile.new()
	setmetatable(newhostile, Boss)

	return newhostile
end

function Boss:ManualOverride()
	self.Conditions.HostileDies.Met = function()
		print"BOSS DIED! WIN!"
	end
end

return Boss

Thanks to @starmaq for the explanation.

1 Like

You can follow through the metatable of newhostile to see where the __index is pointing, at first its __index is set to the Hostile class containing :Spawn(), but then it’s overwritten in the Boss constructor, since you’re setting the metatable to be the Boss class, pointing to methods provided by that class, and not Hostile anymore, and hence :Spawn() does not exist.

1 Like

Bit off-topic, but I just wanna lyk that your iterator functions tutorial was amazing, wud love more advanced tutorials :slight_smile: .

1 Like

Good idea, thanks. Wish I thought of that.

@starmaq Thank you for the explanation too.