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

What is a courotine? Can you give examples of it?

The title says it all. The wiki is not good at explaining it. Can you explain it and give examples?

Thanks

1 comment

0

The article about threading on developer.roblox is low quality and not easy even for intermediate.

1 answer

✓ Accepted answer

Coroutines are basically a global that is used for doing things without yielding the rest of the script. It acts as a whole new script, except in one script. For example:

while wait() do
	print("Hello world!")
end

print("Bob the Builder!")

This would not work as the while wait() loop would keep on looping and never get on to the rest of the script and print "Bob the Builder!" But when we add a coroutine, it changes everything.

coroutine.wrap(function()
	while wait() do
		print("Hello world!")
	end
end)

print("Bob the Builder!")

Now it would print "Hello world!" and "Bob the Builder!"


Another example is:

coroutine.wrap(function()
	wait(5)
	workspace:ClearAllChildren()
end

print("Hello world!")

Without a coroutine, it would wait 5 seconds and then print "Hello world!", but with a coroutine, it prints straight away.


You can also give coroutines variables. For example:

local newThread = coroutine.create(function()
	print("Hola!")
end)

coroutine.resume(newThread)

Wait, why are we resuming the coroutine you may ask. That's because coroutines can be paused by using coroutine.yield(). For example:

local newThread = coroutine.create(function()
	while wait() do
		print("Hola!")
	end
end)

wait(math.pi)

coroutine.yield(newThread)

This would yield the thread (coroutine) after math.pi seconds (3.14159, etc.)


You can ALSO use arguments and parameters with coroutine.wrap(). For instance:

local newThread = corutine.wrap(function(message)
	print(message)
end)

newThread("Namaste!")

Please upvote and accept this answer if it helped.

5 comments

1

Nice answer! :)

0

Thanks.

1

Great answer! Accepted and upvoted!

0

(so basically its like spawn)

1

Yes, but spawn is considered as a bad habit since it has a built-in delay. Some can even be as long as 24 seconds.

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