Coroutine (type)

From ComputerCraft Wiki
Revision as of 15:43, 28 November 2012 by AfterLifeLochie (Talk | contribs) (Moved to CAT:Tutorials.)

Jump to: navigation, search

This is for the coroutine object. For the API, visit Coroutine (API).

Coroutines are objects that allow you to form multiple tasks at the same time.

How to Make a Coroutine

Type 'lua' in the terminal.

To create a variable, you use the function coroutine.create(). Inside the parentheses, you need to add a function. First, make a function:

lua> function helloWorld() for i = 1,10 do sleep(1) print(1) end end

This will create a function named helloWorld that will print a consecutive number every second for 10 seconds. Now that you have a function, create the coroutine using the function:

lua> local c = coroutine.create(helloWorld)

Note that you don't use the parentheses in the command. This is how a function looks like in variable form. Now, let's run it:

lua> coroutine.resume(c)

First, is gives 1, but then returns... "timer"? What's that all about?

the "timer" you see there is a safeguard in case something harmful happens. However, assuming that the safeguard wasn't there, you will be able to both type commands and see the text appear there!


Why Use Coroutines?

Coroutines are used to do multiple things at the same time.

However, only use coroutines when you believe you have no other choice, because many issues can occur with coroutines.