lua-users home
lua-l archive

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


On Mon, Mar 12, 2012 at 19:02, Xavier Wang <weasley.wx@gmail.com> wrote:
> 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
>>
>

You can't store Lua functions themselves in your C library, but you
can store references using luaL_ref(). So if the function you get is a
Lua function (see lua_iscfunction()), store a reference to it.

Or was the problem something else? I'm not clear exactly what you're
having trouble with.

-- 
Sent from my toaster.