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.