id like to know what the difference is between doing a while loop inside of a spawn() and a while loop inside of a coroutine
because i recently changed my scripts to have while loops inside of coroutines instead of spawn() and i wanted to know what the differences was (if any), like if one of them was faster than the other or something
I’ll give as much info as I can on this topic so get ready!
Execution Context
task.spawn is part of the task library (obviously) and it’s used to execute functions asynchronously. It creates a new thread of execution and instantly runs the function.
coroutine on the other hand, gives you options to halt the execution of the thread and resume it later within a single thread.
Concurrency
task.spawn allows you to run multiple functions simultaneously in parallel. Each task runs independently of the others and the task scheduler decides how to allocate resources to execute all functions efficiently.
coroutine cannot run multiple functions simultaneously. They are cooperative, they rely on explicit yielding and resumption to switch between different coroutines. Only one coroutine may execute at a given time.
task.spawn is generally more versatile and more widely used than coroutine but that doesn’t mean that coroutine isn’t great! It just depends on your use case.
tl;dr
task.spawn allows you to run multiple functions at once and is more versatile than coroutine
coroutine while not allowing you to run multiple functions at the same time allows for more control over execution flow within a single thread.
task.spawn = function(ForC, ...)
local thread
if type(ForC) == "function" then
thread = coroutine.create(ForC)
else
thread = ForC
end
coroutine.resume(thread, ...)
return thread
end
The downside is that if the function in ForC uses coroutine.yield(outputs...), you can’t get the outputs out of it, unlike if you use local outputs... = coroutine.resume(inputs...)