I understand how they can be useful but I do not see the difference between using coroutines and simply using functions like spawn(). Can anyone explain what their benefits could be? I don’t want to miss out on an opportunity to use them if they serve a good purpose.
Spawn is simply its name, it spawns a new “thread”. Coroutines are much more powerful, as we can yield a certain function using coroutine.yield()
and resume it using coroutine.resume()
. coroutine.resume()
returns two values, a boolean value based on its success, and a value derived from coroutine.yield
.
I think my question is more of a “what practical use could they serve?” because I can’t think of anything I could apply them to.
You can use it to, in a way, “call” and “return” some type of function. For instance,
function randomizer()
return coroutine.create(function()
local randomNum = math.random()
coroutine.yield(randomNum) -- yield
end
local success, randomNumber = couroutine.resume(randomizer()) -- resume the function
if success then
print(randomNumber)
end
Try this out for yourself to see how this functions.
Oh that’s neat. I could see maybe using this for some type of messaging system, like where it yields and then is called again if the message contains some preselected thing. This makes more sense now, thank you
If I helped out, make sure to solve it as the solution
A huge con to spawn
is its implicit wait()
prior to resuming the thread. You’re missing out on about two whole frames here, which can be prevented by using the coroutine library.