Problems with inheritence

I have a tool module called toolSystem, and a child called foodSystem. toolSystem has a cooldown value

foodSystem contains a method called :eat()

Now in the script

local foodSystem = require(serverStorage.toolSystem.foodSystem)

local newFood = foodSystem.new(3)

newFood:eat() -- this doesnt work and autocomplete only shows :doCooldown() which is from the toolSystem script

toolSystem:

local module = {}
module.__index= module

function module.new(toolCooldown)
	local newTool = {}
	setmetatable(newTool, module)
	newTool.toolCooldown = toolCooldown
	newTool.debounce = false
	
	return newTool
end

function module:doCooldown()
	self.debounce = true
	wait(self.toolCooldown)
	self.debounce = false
end

return module

foodSystem:

local parentModule = require(script.Parent)

local module = {}
module.__index = module
setmetatable(module, parentModule)

function module.new(cooldown)
	local newFood = parentModule.new(cooldown)
	setmetatable(newFood, module)
	
	return newFood
end

function module:eatxd()
	if self.debounce == true then return end
	self:doCooldown()
	
end

return module

The problem is, it’s only setting the metatable of the newTool variable to the Tool System, not the Food System, since you are using module, which is the variables inside of the Tool System. Instead, you should do:

setmetatable(newTool, require(script.foodSystem))

Nevermind i wasnt paying attention, sorry.

but also im gonna have multiple module scripts, like gunSystem, which will handle guns

So you want to include both the Food System and Gun System so that any tool can use either one of them?

yeah, basically

character limit

Sure. What you can do is create a function that joins all modules that you want together.

local function joinAllModules()
	local mergedModule = {}
	for _,moduleScript in pairs(modules:GetChildren()) do
		local contents = require(moduleScript)
		for key, value in contents do
			mergedModule[key] = value
		end
	end
	return mergedModule
end

Then, you can use setmetatable on that function, which will return the merged module.

setmetatable(newTool, joinAllModules())

Note that you have to define the modules variable.

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