lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 11-Mar-05, at 2:49 PM, PA wrote:

Is there any documentation somewhere explaining the limitation of coroutines as far as pcall() & Co goes?

Probably, but let me wrap it up in a nutshell. When the Lua VM calls a C function (including standard library functions), it actually does a regular C function call, which uses the C stack. Some library functions might then recursively call back into Lua, using lua_call, lua_pcall, etc.

The implementation of yield relies on the VM being able to do a regular C return to the caller (of lua_call, lua_pcall, etc.), and the implementation of resume requires it to be able to get back into the context. There are various techniques for accomplishing this, such as swapping C stacks, copying sections of the C stack into the heap to be later restored, etc., but non of them are portable. So Lua doesn't do any of them.

Consequently, you can't yield out of a recursively called instance of the Lua VM.

Mike's interesting patch relies on C functions themselves to be prepared to save their execution context and resume themselves later, and he has provided replacements for those Lua standard library functions which call back into the Lua VM. That's very nifty, in my opinion, but writing a complex C function to allow this sort of thing is tedious.

It has always struck me as ironic that while C is often billed as a sort of "portable assembler", things which would be close to trivial to accomplish in assembler, like coroutines, function closures, and continuations, are painfully difficult if not virtually impossible in C.

R.