lua-users home
lua-l archive

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


Hi lua-l,

I'm writing a lua module in C, to interface with some existing C code.
The existing C code requires the programmer to register many
callbacks. Registering a callback means calling a "register" function
with the following arguments: a function pointer to the callback and a
void pointer (for arguments to the callback). I want to make it so a
lua function can be passed to the "register" function. (This is sort
of similar to the expat example from the lua book, but there are many
unique callbacks, not just three.)

I'm thinking the best approach would be to write one C callback that
calls the appropriate lua function based on the void pointer
arguments. But this is were I run into trouble... how would I actually
do this?

At first I was thinking I would use lua userdata. It's easy to cast
userdata to a void pointer, but then how would I put it back on the
stack, so I can lua_call it? Is it possible to do this, or is this a
dead end? Obviously lua_pushuserdata doesn't exist (and probably
doesn't make sense).

My next though was to make a big table to store all the lua callbacks.
The index into this table could then be stored in the void pointer.

I'm also starting to consider lua_newthread. I could push the lua
function, create a new thread, and then cast the resulting lua_State
to a void pointer.

Is there a batter way that I haven't thought of? I imagine my
situation is fairly common, so people must have seen this before. Do
lua developers prefer one approach over another when it comes to
callbacks?

Thank you all.

-- Tim