It’s of common knowledge that scripts disconnect connections and stop running code once it’s destroyed and for this reason storing scripts under Tools, characters, and others sometimes are just unreliable due to specific parts of code or the whole code needing to be run regardless if it is destroyed or one of its ancestors is.
Even though it’s known that storing scripts under Instances that could get destroyed at anytime is a “bad practice”, some people will still choose to do so for organization method preference.
I am one of the people who sometimes will prefer to organize scripts under characters, Tools, instable objects, etc. Not only because the code the script will run is fine to stop once the script is destroyed, but in general for organization even when the code in the script may break if it’s stopped suddenly.
For this reason I created a module I named IndependentFunction, which will run a passed function in a separate script under ServerScriptService called Processor which should never get destroyed. I use this module across my whole game and it’s just so useful, the best module I’ve made for my game’s specific case.
The module works fine, but I’m not yet fully satisfied with it. I would like to know if there are ways I didn’t consider yet of improving its use, such as quality of life changes or even code optimization. I would also like to know it would be good for other developers if I just posted this module in Community Resources as an open-source module, because even though it’s an extremely simple module with a total of less than 20 lines of code, a lot of people just never considered making something similar that I know of.
Module in .rbxm:
IndependentFunction.rbxm (1.7 KB)
Copied and pasted code:
- IndependentFunction -
local runFunctionEvent = script.RunFunction
local independentFunction = {}
function independentFunction:Run(func: () -> nil)
runFunctionEvent:Fire(func)
end
return independentFunction
- Processor -
local runFunctionEvent = script.Parent.RunFunction
runFunctionEvent.Event:Connect(function(func: () -> nil)
func()
end)
This module in my game is used a lot to run delayed threads by task.delay()
or coroutine.resume()
. Since sometimes I need to also reference to the thread in a variable and the module actually creates a new scope to run the yielded thread, I wanted to do some small optimization by making :Run()
return the thread if the first argument is a thread instead of a function, but it didn’t really work because you can’t pass threads through BindableEvents. If there’s a suggestion specifically to how I could do this, it would be really appreciated.