Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

What is a Coroutine?

Asked by 10 years ago

I checked out the scripting glossary and I found out that a Coroutine is basically a script running inside a script..

"A coroutine is a routine outside the main routine of the script. It executes its own code whilst the main (script's) routine executes as well, therefore having two routines by one thread - multitasking! You aren't limited to 'only' have one coroutine."

I want to know how to use Coroutines, how would I go about doing so?

2 answers

Log in to vote
2
Answered by 10 years ago

To use coroutines, you are going to want to use the coroutine library.

function some_func()
    while wait(2) do
        print('hi')
    end
end

local routine = coroutine.create(some_func)

coroutine.resume(routine) -- This doesn't yield

print("Test") -- prints instantly

You can also make use of the Spawn and Delay functions to easily create another routine without all of the hassle of the coroutine library.

Spawn(function()
    while wait(2) do
        print('hi')
    end
end)

print("Test") -- same effect as above
0
Thanks, this helped a lot. What would coroutine.resume(routine) Do? IntellectualBeing 430 — 10y
0
It starts (or "resumes") the coroutine. You can use coroutine.yield(...) to stop the coroutine's execution, and then coroutine.resume(routine, ...) to start it again. When you first create the coroutine, it does not auto-start, so you must "resume" it. User#11893 186 — 10y
Ad
Log in to vote
-1
Answered by 10 years ago

Let's say you want two functions:

function hi()
    for i=1, 100 do
        print "HELLO"
        wait(.1)
    end
end

function spam()
    for i=1, 100 do
        Instance.new("Part", workspace).Position = Vector3.new(0, 100, 0)
        wait()
    end
end

If we tried this, we would get a 10 second delay before it started raining bricks, because the script wants to finish printing HELLO first:

hi()
spam()

This is where Spawn(), Delay(), and coroutines come in handy:

Spawn(hi())  -- Spawn tells the script to send the function to the task scheduler, and moves on with the rest of the script.
spam()
Delay(1, hi())  -- Just like spawn, except, in this example, there is a 1 second delay before hi goes.
spam()

Explaining coroutines probrobly wouldn't fit on this webpage, so see if this helps.

(Just remember with coroutines that you can't reuse a "dead" coroutine)

3
This answer isn't completely correct. You also have a syntax issue in your Spawn and Delay examples which will prevent you from getting the desired result. Not to mention the fact that you didn't even mention the actual coroutine library. User#11893 186 — 10y
0
Whoops, you're right! I think I should go to bed. DiamondBladee 135 — 10y

Answer this question