lua-users home
lua-l archive

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


then how to store this structure? if i using malloc, then when i free this structure? if i use userdata, when i unanchor it?

在 2012-3-13 上午9:06,"Alex" <initrd.gz@gmail.com>写道:
Why not just make a struct that contains a pointer to both items?

2012/3/12 Xavier Wang <weasley.wx@gmail.com>

i have a similar problem, that is there are only one void poiner argument to callback, but i need pass two (lua_State and userdata),,. :(

在 2012-3-13 上午8:18,"Tim Perkins" <tprk77@gmail.com>写道:

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