Coroutines in Lua

Link: The Lua folks discuss their implementation of coroutines, using Create, Resume and Yield methods.

Lua implements the concept of asymmetric coroutines, which are commonly denoted as semi-symmetric or semi-coroutines. Asymmetric coroutine facilities are so called because they involve two types of control transfer operations: one for (re)invoking a coroutine and one for suspending it, the latter returning control to the coroutine invoker. An asymmetric coroutine can be regarded as subordinate to its caller, the relationship between them being similar to that between a called and a calling routine.


Lua coroutine facilities provide three basic operations: create, resume and yield... Function coroutine.create creates a new coroutine, and allocates a separate stack for its execution... Function coroutine.resume (re)activates a coroutine, and receives as its required first argument the coroutine reference... A coroutine suspends by calling function coroutine.yield in this case, the coroutine’s execution state is saved and the corresponding call to coroutine.resume returns immediately.

The main difference with typical thread implementations is that (a). the caller is suspended until completion and (b). a coroutine can return values like a function call. I suppose I'd summarize it as functions that retain state between calls.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

BCPL coroutines

In the appendix they show how to implement symmetric coroutines in Lua. Which brings me to BCPL, and a paper you may be able to obtain from Martin Richards.

"Implementing dependable process control applications using BCPL coroutines and Cintpos"

See a bunch of references to the BCPL paper

Not able to find it anywhere openly available. Probably in the ACM collection somewhere.

Not published

iirc the paper wasn't accepted for software practice & experience. I went to the source.

Poplog "Processes"

The coroutine mechanism of Poplog, and hence Pop-11, is basically the same as the one described here for Lua. Poplog's documentation unfortunately calls these "processes" rather than coroutines. Coroutines can be suspended with the procedure "suspend" and resumed with "resume". Both suspend and resume permit passing an arbitrary number of values between caller and callee.

The differences between Poplog the scheme described for Lua lie in the creation of coroutines. In Poplog not only can you create a coroutine from a procedure but also from another coroutine or simply from a snapshot of the current state.

The ability to copy a coroutine exposes the issue of whether coroutines share their environments i.e. local variables. In Poplog, coroutines do not share their local variables - otherwise assignment becomes dangerously uncontrollable.