I can't understand what's coroutine.yield()

Hello, I know there’s post about coroutines, but I still can’t get what coroutine.yields() do, like, it stops it or it runs it? I don’t get it, any help will be apreciatted,

This is what devwiki says:
coroutine.yield() puts your coroutine in suspended mode, where it just stops and waits until the coroutine is called again. coroutine.yield() cannot include a metamethod, C function or an iterator (if you don’t know what those are then you’re most likely not using them). Anything extra put inside a coroutine.yield() will go straight to coroutine.resume()

So, it suspends it? I don’t get it, how do I resume it, with coroutine.resume() and then courtoutine.yields breaks? I don’t get it!!!

2 Likes

coroutine.yield stops your coroutine until an outside force starts it again.

local coro = coroutine.create(function()
    print('wow I started')
    coroutine.yield() -- stops 
    print('wow I resumed')
end)

coroutine.resume(coro) -- does first print, yields, returns here
coroutine.resume(coro) -- does second print before `coro` dies

Any arguments you pass to coroutine.resume are returned by coroutine.yield, and any arguments passed coroutine.yield are returned by coroutine.resume.

16 Likes

Oh, so, It can stop, at any time, and it will resume since last .yield?
Also, what will you recommend me to do this, like to use couroutines?

Coroutines tend to be useful to dispatch separate tasks that may yield, because it won’t yield the thread you created them from. However, coroutine usage can be very niche at times and if you don’t find yourself needing them you shouldn’t go out of your way to use them. It really just depends on what you’re making.

4 Likes