Skip to content

Instantly share code, notes, and snippets.

@zacharyvoase
Created May 4, 2009 10:56
Show Gist options
  • Save zacharyvoase/106417 to your computer and use it in GitHub Desktop.
Save zacharyvoase/106417 to your computer and use it in GitHub Desktop.
-- An implementation of call-with-current-continuation in Lua.
-- (c) 2009 Zachary Voase
function callcc (fun)
function coro ()
-- The coroutine which will hold the value with which it is called, then
-- yield it back again later.
local val = coroutine.yield()
coroutine.yield()
coroutine.yield(val)
end
cont = coroutine.create(coro)
coroutine.resume(cont) -- Gets us to the first coroutine.yield() call.
-- Callback sends the args it is called with into the coroutine.
function callback (...)
return coroutine.resume(cont, arg)
end
fun(callback)
-- Status and value pulled out of the coroutine.
local status, value = coroutine.resume(cont)
return unpack(value)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment