[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Another userdata question
- From: Jean-Luc Jumpertz <jean-luc@...>
- Date: Wed, 13 Nov 2013 09:04:30 +0100
Le 12 nov. 2013 à 21:48, Geoff Smith <firstname.lastname@example.org> a écrit :
> I am really hoping someone could help me with this question please as I am totally stuck on it for now.
> I am trying to implement a userdata via the C API, to give me this type of functionality
> btn1 = graphics.newButton(x,y,width,ht, "pressMe")
> That's OK I think I have got that figured out and largely working, but the next thing I want to do is call a user defined Lua action function on the button instance. For example
> In Lua
> function btn1:action(someArbitrayParamBackFromC)
> print("ouch someone just poked btn1")
> How can I call that Lua button instance function from C when I have detected the key is pressed ?
Actually the answer to your question will depend on the external context, i.e. the external library that shall call your button action.
But the general pattern for this type of interaction is to provide a C function to your C environment that will be used as a callback when the button is pressed.
BTW this is similar to the example you gave with the timer.
Of course, you need to adapt this to your use case, but here are the steps I would use in this case
1) in create a simple Lua function encapsulating the call to btn:action and taking the button instance as an upvalue
function externalButtonCallback (someArbitrayParamBackFromC)
2) get a reference to this externalButtonCallback with luaL_ref(L, LUA_REGISTRYINDEX), and store this reference in a C proxy structure.
This is actually the part that heavily depends on your graphic library context.
3) when the button is pressed, call the Lua function from C:
lua_rawgeti(L, LUA_REGISTRYINDEX, yourRef); /* get your Lua function back */
lua_pushxxx (L, theArbitrayParamBackFromC); /* push the parameter */
lua_(p)call (L, 1, 0); /* call the Lua function */