lua-users home
lua-l archive

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


Hi,

David Morris-Oliveros wrote:
> It would be similar to the hooks in lua, but rather lua calling the hook 
> every 5 instructions, i let it execute those 5 instructions, then it 
> comes back to me.

That's inversion of control. Lua already supports that with the
help of coroutines. And lucky you, you can yield from a count hook
(or line hook).

So from C do a lua_newthread() and then lua_sethook() to install
your count hook. When the hook decides that the timeout is reached
it forces a yield for the coroutine with 'return lua_yield(L, 0)'.

Resuming (starting) the new coroutine will return with LUA_YIELD,
(at least in Lua 5.1) so you know it's not done yet. To continue,
just resume it again. You can of course have many different
coroutines at the same time or just recycle a few of them.

Alas, there is no (easy) way to differentiate a yield from a hook
with a yield from the Lua function itself. So you have to decide
for one feature or the other.

Note that the count hook slows things down. Also note that
coroutine.resume() and lua_resume() work subtly different.
Have a look at the manual first and then check lbaselib.c.

Oh, and BTW: do not mix coroutine.resume() (the Lua function)
with yielding from the line or count hook. It rips apart the
stack frame of the running Lua function. You really have to use
lua_resume() from C and carefully avoid touching the coroutine
stack.

Bye,
     Mike