Hi everyone,
I’m building a ModuleLoader in Roblox that goes through all my Handlers (ModuleScripts) and calls their .Start() function if it exists. My loader works fine for normal handlers, but I have a problem:
If a .Start() function contains an infinite loop or yields forever, the loader gets stuck and can’t continue loading the remaining services. Using pcall only catches errors, but it doesn’t help with blocking functions.
Here’s my loader (very simple):
local Loader = {}
function Loader.Load(Services : {ModuleScript})
for _, Service in Services do
local Success, Result = pcall(require, Service)
if Success then
print("[MODULE-LOADER]: Service: '"..Service.Name.."' Loaded.")
else
warn("[MODULE-LOADER]: Service: '"..Service.Name.."' Failed to load. Error:", Result)
continue
end
if Result.Start then
local Success, ErrorMessage = pcall(Result.Start) -- If Ts Yields, the Loader Yields too
if Success then
print("[MODULE-LOADER]: Service: '"..Service.Name.."' Started.")
else
warn("[MODULE-LOADER]: Service: '"..Service.Name.."' Failed to Start. Error:", Result)
end
else
print("[MODULE-LOADER]: Service: '"..Service.Name.."' has no Start function.")
end
end
end
-- No get function. Services get other modules with require for autocomplete, not that deep gng
return Loader
My only Solution was This:
local Success, ErrorMessage = pcall(function()
task.spawn(Result.Start)
end)
But I don’t think this will catch errors inside Result.Start, because pcall only wraps the call to task.spawn. Since task.spawn runs Result.Start in a new thread, pcall returns immediately and cannot detect any errors that happen inside Result.Start itself.
Goal
If a .Start() function yields, the Loader will print that a specific functions yields,
and it will just continue looping trough the Handlers.