To those good with COROUTINES:

Hey all,

I was wondering, to those of you who have a great handle on Coroutines, where was your best source of instruction? I’ve got a handle on most of what I had to learn about Lua, but haven’t tackled coroutines yet.

Was there a particular tutorial / website / source you found most useful for coroutines?

I think I’m especially wondering When Do I Use Them? So it would also be helpful if you could list the times you use coroutines?

Hm…How is coroutine different from Spawn?
Thanks much.

1 Like

Spawn is built in old 30Hz pipeline same with delay etc. and yields.
And overall you have more functionalities with coroutines such as coroutine resuming, get their state etc.

And you are using them for making new thread example of that is for loop

for i = 1,3 do --this will create new thread for every i
coroutine.wrap(function() 
print(i) 
wait(10) 
end)() 
print("Hey") --this will print immediately
end

for i = 1,3 do --this won't create new thread for every i
print(i) 
wait(10) 
print("Hello") --this will print after 10 seconds
end

Please correct me if I am wrong.

4 Likes

I didn’t use any sources. I just messed around with it and figured it out. A coroutine is basically just spawn(), but better. More functions to it & it instantly executes, unlike spawn().
But unlike a spawn(), coroutines don’t instantly run. To make them instantly run, you can do one of two:

coroutine.resume(coroutine.create(function()
	--code goes here
end))
--or
coroutine.wrap(function()
	--code goes here
end)() -- the last () is to actually run the coroutine

Coroutines are nothing else than a better version of spawn(), but with slightly more complications.
They do have more stuff to it such as: .isyieldable; .running; .status; etc, but I personally don’t use them a lot and there probably won’t be many situations where you would want to use them.

3 Likes

Just a side note to the previous replies:
Despite what you may think about coroutines, they do not run simultaneously to other coroutines/functions. They still consume processor time independently, however the way in which Roblox delegates processor time to coroutines and regular code, makes it appear to run simultaneously to the rest of the code.

Just keep that in mind when you are using coroutines to make a lengthy process run much faster, perhaps. But if you are wanting a system that can physically run code simultaneously, then maybe take a look at the new actors feature that is currently in BETA.

Good luck anyways!

3 Likes