Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

No useful way to learn coroutines?

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.

6 comments

0

What resources have you looked at?

0

I looked at the roblox wiki article and it wasn't much help

0

You could check for questions answered on this topic using the search bar. Something like this just by searching "Coroutines": https://scriptinghelpers.org/questions/10455/question-about-coroutines

0

I always thought https://www.lua.org/manual/5.1/manual.html#2.11 made a lot of sense.

0

The roblox wiki is not for learning Lua. The PiL is. There's other sites to learn Lua as well. Such as lua-users.org

2 answers

✓ Accepted answer

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

This discussion is preserved as it was. New answers, comments, and votes are closed.