You can preserve the function names either by having just one function per ModuleScript like you show, and name the ModuleScript identical to the function, e.g.:
In a ModuleScript named “functionToInherit”
return function()
print("functionToInherit printed this")
end
And in your Interaction class module you have:
function Interaction.HandleFunctions()
for _, module in pairs(script.Functions:GetChildren()) do
if not module:IsA("ModuleScript") then
continue
end
Interaction[module.Name] = require(module)
end
end
After the Interaction.HandleFunctions()
is called once, Interaction.functionToInherit()
can be used, but this trick limits you to one function per ModuleScript which is a waste of Instance memory.
It would be nicer to not use the ModuleScript name for anything, and instead have the function modules return tables with 1 or more named functions, like so:
In a ModuleScript named whatever you want:
return {
functionToInherit = function() print("functionToInherit printed this") end,
add2Numbers = function(a,b) return a+b end,
}
Then in your main module:
function Interaction.AddFunctions()
for _, module in pairs(script.Functions:GetChildren()) do
if not module:IsA("ModuleScript") then
continue
end
local newFunctions = require(module)
for functionName, func in pairs(newFunctions) do
Interaction[functionName] = func
end
end
end
There are ways to do this a bit more elegantly, but these fit your existing structure. You should of course also add checks to make sure modules are not trying to add different functions with the same name.
P.S. in your example you have IsA("Module")
which will not work. I have changed this to IsA("ModuleScript")
in my copies of your example.