How To Use Coroutines

From ComputerCraft
Jump to: navigation, search

Coroutines are Lua's way of handling concurrency - running multiple things "at once". They act somewhat similarly to threads on computers, except coroutines must explicitly transfer control back to their parent - only one is actually run at any given time. This is what coroutine.yield does. Many things internally use coroutine.yield, such as os.pullEvent, sleep and anything else which waits for events.

You can create a coroutine with coroutine.create - pass it a function and it will return a coroutine. This coroutine will initially not be running (use coroutine.status to check its status - it should show "suspended"). Pass it along with some arguments to coroutine.resume and coroutine.yield will return those arguments. Any arguments passed to coroutine.yield will be returned along with a boolean value indicating whether the coroutine errored during execution (if it did, however, an error message will be returned instead).

See also the Lua Users wiki.