Hi so, I recently noticed that people normally have a hard time cleaning up threads as well as people having a hard time getting used to the task library due to it being way faster and more performant then the coroutine library.
Like the cleanup method for coroutine library. I made a small function where it uses xpcall and creates and runs a given function as a thread, then like coroutine.yeild and coroutine.close it defers then cancels the thread.
This thread will then be unable to be referenced but It’s safe to recall the function and create a new thread.
Here is the function:
Function
type thread = RBXScriptConnection
return function(fn: RBXScriptConnection) : thread
local t: thread
local function rThread(...)
xpcall(function(...)
t = task.spawn(fn)
task.defer(task.cancel, t)
end, function(...)
error(`error during thread execution`)
end)
end
rThread()
end
If you’d rather clean it up yourself, thats fine but this is a safe way to also make threads and clean it up.
Also here is the module if u dont know where to write it!
ProtectedSpawn.lua (312 Bytes)