  lua-l archive

• Subject: Re: Coroutines Again :)
• From: Maria Julia Dias de Lima <mjulia@...>
• Date: Thu, 28 Dec 2000 12:45:38 -0200 (EDT)

```Hi,
I've been making some experimental implementation of
continuations in Lua as part of my PhD thesis.

I have just made some preliminary tests and there are
some restrictions that are not my focus (at least, for the
time being). One of them is performance.
Another one is that our continuation involves only  the Lua stack,
so it doesn't capture stacks that cross Lua -> C -> Lua calls.
Another assumption is that the local variables remain in the stack,
so when a continuation is called, it uses the same values which
were on the stack when the continuation was created.

A continuation is created as a userdata and we used a syntax similar
to setjmp and longjmp functions:  getcont and callcont.
The following example illustrates coroutines using continuations in Lua.

===
function a()
write ("Starting A\n")
co_a.transfer(co_b)
write ("Back to A\n")
co_a.transfer(co_b)
write ("Finishing A\n")
co_a.transfer(co_b)
end

function b()
write ("   Starting B\n")
co_b.transfer(co_c)
write ("   Back to B\n")
co_b.transfer(co_c)
write ("   Finishing B\n")
co_b.transfer(co_c)
end

function c()
write ("      Starting C\n")
co_c.transfer(co_a)
write ("      Back to C\n")
co_c.transfer(co_a)
write ("      Finishing C\n")
co_c.transfer(co_a)
end

function coroutine(f)
self={}
self.cont=nil
self.func=f
transfer = function(prala)
local x = getcont() -- creates a continuation
if x then
%self.cont=x
prala.resume()
end
end

resume  =  function ()
if (%self.cont==nil) then  -- if no continuation
%self.func()
else
callcont(%self.cont)  -- call the target continuation
end
end
return {transfer=transfer, resume=resume}
end

co_a = coroutine(a)
co_b = coroutine(b)
co_c = coroutine(c)

co_a.resume()

===

This current implementation of "Lua with continuations"