call/cc in Lua - Possible?
I guess you forgot the part about writing your program in continuation passing style. Once you do that, call/cc is trivial (in Lua or in any other language), as the continuation will be an explicit parameter to all functions (call/cc included).
PS: besides closures, you also need proper tail calls to program in continuation passing style.
Answering the question about plans for call/cc in Lua: There are no plans for call/cc in Lua. Capturing a continuation is either too expensive or require some code analsis well beyond what the Lua compiler can do. There is also the problem that Lua continuations may include parts in C.
With coroutines, however, we can already implement call/cc1 in Lua (one-shot continuations). That is good enough for many uses of continuations.
There are two prerequisites to manually implement call/cc per the Wikipedia quote:
- the language must support closures
- you must write your program in continuation passing style (CPS)
I suspect you will not like #2.
To write your program in continuation passing style:
- Every function must take a continuation argument
- Functions must return by calling their continuation
So, using k
as the name of the continuation argument, a function would look like:
function multiplyadd(k, x, y, z) return k(x * y + z) end
The toplevel might use print
as its continuation, so invoking multiplyadd
at top level would look like:
multiplyadd(print, 2, 4, 1)
With that scaffolding we could define call/cc as
function callcc(k,f) return f(k,k) end
Note that the above multiplyadd
actually cheats since *
and +
are not in CPS. It is very tedious to add all the operators in CPS form, replace all the Lua library functions with CPS equivalents, and translate/generate all your code to CPS; see details here.