

A Field Guide to Lua Coroutines - silentbicycle
http://spin.atomicobject.com/2013/07/01/lua-coroutines/

======
fab13n
Coroutine are a powerful low-level tool to build higher level, user friendly
environments. That's true of most of Lua's advanced features, BTW: they tend
to be complex tools letting you build simple-to-use stuff (as opposed e.g. to
C++'s templates, where you need a fairly advanced understanding of C++
metaprogramming features to use even simple containers correctly).

Anyway, coroutines are intended to let people build their own high-level
concurrency system. It's used e.g. to share the CPU among scripted entities in
video games.

Mihini ([http://www.eclipse.org/mihini/](http://www.eclipse.org/mihini/))
offers higher-level concurrency within a single OS thread, primarily
targetting Linux-based embedded communicating applications.

Copas
([https://github.com/keplerproject/copas](https://github.com/keplerproject/copas))
is much simpler, but probably sufficient if you only need to handle several
sockets concurrently without wasting many OS threads.

There are also some attempts to wrap luvit
([https://github.com/luvit/luvit](https://github.com/luvit/luvit)), Lua's
porting of libuv, with coroutines, getting callback-based performances without
it's tendency to make one's code write-only. I don't know what's usable and
maintained, nor even whether it really exists.

~~~
catwell
Luvit is not really a port of libuv, it is more a reimplementation of the
NodeJS model that uses libuv.

A more straightforward libuv binding by the same author is
[https://github.com/creationix/luv](https://github.com/creationix/luv), and
one using coroutines is
[https://github.com/hnakamur/couv](https://github.com/hnakamur/couv)

------
vaughan0
> "The main limitation of Lua coroutines is that, since they are implemented
> with setjmp(3) and longjmp(3), you cannot use them to call from Lua into C
> code that calls back into Lua that calls back into C, because the nested
> longjmp will clobber the C function’s stack frames. (This is detected at
> runtime, rather than failing silently.)"

Lua 5.2 provides a mechanism to help with this:
[http://www.lua.org/manual/5.2/manual.html#4.7](http://www.lua.org/manual/5.2/manual.html#4.7)

~~~
silentbicycle
Thanks. :) I'm still mostly using Lua 5.1.4 most of the time, and I forgot to
include that.

~~~
dottrap
There is also a modification patch for Lua 5.1 called Cocos that fixes this.
It was written by Mike Pall, better known as the author of LuaJIT.
[http://coco.luajit.org](http://coco.luajit.org)

~~~
silentbicycle
I saw a patch he wrote for copying coroutines, for those who miss multi-shot
continuations.

------
beagle3
Relevant: super lightweight co-routines in C, with (limited) support for
blocking as well:
[https://github.com/halayli/lthread](https://github.com/halayli/lthread)

