Hello, I have recently been trying to shift over into a more OOP style of coding in roblox and I have come up with a base structure which I would like to know your opinions on. It works as I have been making a test game the past couple days trying to use this style but there are some issues I am having which I will mention below. The code I am about to show is just something I made up to show how I have set it up.
Module that “initializes”
local setup = {}
setup.__index = setup
function setup:Init()
for _, mod in pairs(script.Parent:GetChildren()) do
if mod ~= script and mod:IsA("ModuleScript") then
setmetatable(require(mod), setup)
end
end
end
return setup
Module which creates the object
local mod1 = require(script.Parent.Init)
mod1.__index = mod1
function mod1.newObj(killOnTouch)
local obj = {}
setmetatable(obj, mod1)
local part = Instance.new("Part")
part.Anchored = true
part.Color = Color3.fromRGB(0,0,255)
obj.Part = part
obj.CanKill = killOnTouch
if obj.CanKill then obj:ConnectKillFunction() end
return obj
end
return mod1
Module which has events for the object
local mod2 = require(script.Parent.Init)
mod2.__index = mod2
function mod2:ConnectKillFunction()
local part = self.Part
local c = part.Touched:Connect(function(hit)
if game.Players:GetPlayerFromCharacter(hit.Parent) then
hit.Parent.Humanoid:TakeDamage(100)
end
end)
self.KillEvent = c
end
function mod2:ChangeColor(color)
self.Part.Color = color
end
return mod2
Script that calls the initial module and also creates the object and changes its color
local Settings = require(script.Parent.Init)
Settings:Init()
local block = Settings.newObj(true)
block:ChangeColor(Color3.fromRGB(255,0,0))
The end result should be a part which is red and kills on touch
Now the problem I have encountered is I am not sure how to call functions only in modules that have the function. To better explain lets say there is a third module with the code below:
This module sets up a player added function
local mod3 = require(script.Parent.Init)
mod3.__index = mod3
function mod3.Setup()
game.Players.PlayerAdded:Connect(function()
mod3.newObj(false)
end)
end
return mod3
This is the new initialization module which does not work
local setup = require(script.Parent.Init)
setup.__index = setup
function setup:Init()
for _, mod in pairs(script.Parent:GetChildren()) do
if mod ~= script and mod:IsA("ModuleScript") then
local tab = require(mod)
setmetatable(tab, setup)
if tab.Setup then tab.Setup() end --basically i want to call the setup functions in modules that have it, but if they dont have it then nothing happens
end
end
end
return setup
I tested this and another way earlier and it ended up with the game freezing so I am not sure how I would go about this. Another solution is to manually call the setup function for the specific modules but I feel like their might be a better way which I am missing.
I am very new to this so I am sorry if something I am doing is really bad but thanks anyways for reading!