lua-users home
lua-l archive

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


Hi,

I am about to hit a similar problem, I haven't implemented it yet, but my intended solution is to create a table with all of the callbacks within lua and then call a set_handler function passing the table as an argument. The set_handler function is implemented in C and sets a field of the lua registry equal to that table. I have a single callback function in C, it looks up the value in the registry to get the callback table in lua, it then indexes that table to find the appropriate function to call, and calls it.

Thanks,
Kev
 
On 13 Mar 2012, at 00:18, Tim Perkins wrote:

> 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
> 
>