[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: [ANN] Rembulan, an implementation of Lua 5.3 for the JVM
- From: Miroslav Janíček <mira.janicek@...>
- Date: Sat, 1 Oct 2016 23:27:07 +0200
> On 1 Oct 2016, at 21:29, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
>
>> Rembulan is an implementation of Lua 5.3 for the Java Virtual Machine (JVM), written in pure Java with minimal dependencies.
>>
>> [...]
>>
>> Comments, suggestions, or contributions are welcome!
>
> (How) did you implement coroutines?
I did.
Every Lua function is an object with two methods, corresponding to two entry points:
* invoke — when the function is called;
* resume — when the function is resumed once it has been paused.
I use exceptions (I call these “control throwables”) for non-local control flow: on every level that corresponds to a Lua call, there is an exception handler that catches the control throwable, registers the call frame with it, and rethrows the throwable. This way the actual Java call stack is unrolled all the way to the (outer) invocation point, reconstructing the Lua call stack in the process.
When the control exception is a coroutine switch, the reconstructed Lua call stack is stored into the current coroutine object, and the “target” coroutine is resumed (see below).
Non-dead, non-suspended coroutines are organised in a stack, with the current (running) coroutine being the top of this stack. coroutine.resume pushes the target to the coroutine stack, coroutine.yield pops the coroutine stack.
Resuming a coroutine C is as simple as taking the top T of the call stack stored in C, and resuming T (by calling T’s resume). If no control exception is thrown, T has returned; we can then continue with the previous call frame, i.e., the call frame that called T’s invoke. The process is repeated until C’s call stack is empty. At that point, the C is popped from the coroutine stack, and the previous coroutine is resumed.
So it’s quite different from the way (PUC) Lua does this, at least according to “The Implementation of Lua 5.0” (I haven’t studied the Lua sources to see whether it is still the same, though). Rembulan effectively has a coroutine dispatcher whose job it is to resume the right coroutine.
M.