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

What is Coroutine?

For a long time life of Lua, one thing that is really makes me to ask. What is Coroutine and other Coroutines? This kind of Lua that I want to be use at my scripts? Please help me!

1 answer

Well basically, a coroutine is a ROBLOX function that breaks the Lua sequence. What does this mean? Well, let's say you had two while true do loops, like so:

while true do
	--Code here
end

while true do
	--Code here
end

Now, we both know that this won't work, because scripts are read in a sequence (top to bottom). The first loop is going to keep executing code until it stops (which it won't), and then it will move onto the code under it, which is the second loop. But with coroutines, we can allow two or more loops to run at once.

coroutine.resume(coroutine.create(function()
	while true do
		--Code here
	end
end))

while true do
	--Code here
end

Now I know this might look confusing at first, but it's really not. What the coroutine is doing, is that it's sort of "breaking" the scope away from the sequence. So the script will read the code from top to bottom, see that there is coroutine, and run the code as if the first while true do wasn't even there. For example:

coroutine.resume(coroutine.create(function()
	while true do
		print("This was printed under a coroutine!")
		wait(1)
	end
end))

while true do
	print("This was not")
	wait(2)
end

Basically, what this is going to do is that it's going to print "This was printed under a coroutine!" every second, and at the same time print "This was not" every two seconds. This can be very useful if you want multiple scopes working at once. For more information on coroutines, click these two links: Beginners Guide to Coroutines or Coroutine Tutorial. Hope this helped!

1 comment

2

The word you are looking for is 'thread'. Coroutines run in their own threads, as do individual Scripts and LocalScripts.

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