So I recently decided to start learning coroutines but there isn't any useful articles or posts that are explained in a way that is easy to understand.
Think of coroutines as a seperate script that you can talk to from the main script.
You create them with
cr = coroutine.create( function() end )
You start them with
coroutine.resume(cr)
You can also put pauses into coroutines by using something like
cr = coroutine.create( function() print("foo") coroutine.yield() print("bar") end)
At first it does nothing until you start it with
coroutine.resume(cr)
It'll only print "foo" at first. Next you'll need to see if the coroutine is ready to be ran again.
while coroutine.status(cr) == "running" do wait() end coroutine.resume(cr)
This is because the coroutine and your main script are running at the same time, so it's not for sure whether the script will reach coroutine.yield in the coroutine code first, or your script will try to resume the coroutine first.
In addition to "Running" coroutines can be "suspended" meaning they've got to a yield, or "dead" meaning they reached the end of their code.
For more advanced uses you can pass information to a coroutine with coroutine.resume(cr, info), and coroutine.yield(info), anything extra will return to it's counterpart. E.g. anything in yield() will return to the first resume(cr), and resume(cr, info) will send info to be returned by where the yield() currently is.
For coroutine.resume(), this information is passed to the second set value, the first is reserved for if it ran successfuly, kinda like pcall.
success, info = coroutine.resume(cr)
You can also create a coroutine into a function using resume = coroutine.wrap(function() end)
anything passed to resume(args) will be passed to the current yield()'s return, and anything passed in yield will return when the function's called. It also has different error propogation, if the coroutine errors your main script errors, unlike with .create and .resume
Coroutines are pretty basic when you read about them but in practice they're a bit more tedious. You wont find much info about them on the wiki so the best way to learn is to find tutorials with situations where they are used in actual situations so that you get an idea on how to use them.
try these out: