lua-users home
lua-l archive

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


Le 12 nov. 2013 à 21:48, Geoff Smith <spammealot1@live.co.uk> 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")
> end
>  
> 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)
		btn1:action (someArbitrayParamBackFromC)
	end

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

Jean-Luc