Coroutine (type)

From ComputerCraft Wiki
Revision as of 23:35, 31 December 2012 by Pokepal101 (Talk | contribs) (Fixed example code. Added {{NeedsWork}}.)

Jump to: navigation, search
This page needs some serious TLC, stat!
Please help us by cleaning it, fixing it up, or sparing it some love.
(Reason: Why is the safeguard there? What is its purpose? Pokepal101 03:35, 1 January 2013 (MSK))

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(i) 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.