Coroutines in Lua

What is a coroutine?

Coroutines are like functions. They start a little bit the same way. However, inside one, you'll eventually hit upon a statement such as yield! The coroutine will store the place where it was, and give back control to the main running thread. Or another coroutine, too! You can then later resume it (and give a few extra arguments if needed) for it to do its other stuff.

This is obviously HUGE. Say you want Little Jimmy to say 'Alright' after Julia says 'The football is on that chair.'. Wouldn't it be nice if we kept the function for Jimmy's speech tidy in its own place, same for Julia? Make them coroutines. After one says something, yield control to the other, until the conversation is finished and we go on as usual.

Without coroutines, you have to be constantly keeping track of bigger and bigger state and constantly ask which one you're in. With coroutines, you need only to take care of yours and give/receive control.

Lua's Offering

With Lua, you first must create a coroutine with coroutine.create(), which you pass a function to. This can be any function of yours you made, or an anonymous function! Simply pass a definition of one in there.

routine = coroutine.create(
    print("Hello fella!")
    print("I'm paul!")

coroutine.resume(routine) -- "Hello fella!"
coroutine.resume(routine) -- "I'm paul!"
-- Coroutine is done!

Want to give the coroutine extra info once resumed? Pass stuff on your coroutine.resume and make values on the coroutines' end to recieve what coroutine.yield() will, well, yield! You think you can go bonkers with this power? You can. Just check out how someone made a task/signal system out of them!

More info

Official Lua tutorial on their usage

Wikipedia's take on them

A C implementation using trickery!