I am trying to have a coroutine to close itself:
local someCoroutine
local function stuff()
for i = 1,5 do
print(i)
task.wait(0.1)
end
end
local function cleanup()
coroutine.close(someCoroutine) -- errors "cannot close running coroutine"
-- do some cleanup stuff
end
someCoroutine = coroutine.create(function()
stuff()
cleanup()
end)
coroutine.resume(someCoroutine)
What I am trying to achieve is create a thread that runs a function. After the function terminates, it does a cleanup, which essentially closes the thread as well.
Apparently that is not possible when cleanup()
and stuff()
is under the same thread. Since a thread is considered running when running cleanup()
and running threads can not be closed (why?).
If I add put coroutine.close
under another thread, AND a task.wait()
, it has no errors, which is quite a “hacky” fix.
local function cleanup()
coroutine.wrap(function()
task.wait() -- without this it errors "cannot close NORMAL coroutine"
coroutine.close(someCoroutine)
end)()
end
Is there any workaround without this “hacky” fix? In my case, there might be situations where I have to assure that the thread is completely closed before continunning.