lua-users home
lua-l archive

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


It was thus said that the Great Laurent FAILLIE once stated:
> Hello,
> I'm working on a C programs using Lua as embedded language.
> At Lua side, I'm defining a table on witch a filed need to be a function as :
> _, err = Broker:subscribe { 
>         { topic = "/tata", function = myfunc }, 
>         { topic = "tutu", function = func2 }}
> And I know at C side I have to look up for TFUNCTION for "function" field.My reading function is creating a structure containing 
> - a string, the topic, 
> - and a "reference" or something to keep track of the function
> 
> now my question :1/ How can I store TFUNCTION at C side ?2/ How my C code can "call" this Lua function ?
> If it's not so clear, please have a look on my code here : https://github.com/destroyedlolo/Selene/blob/master/src/MQTT.c
> especially on line 79.
> Thanks
> Laurent

  There are a few ways to do this.  The easiest way is to store it in a
global variable in the Lua state:

	static int foo(lua_State *L)
	{
	  luaL_checktype(L,1,LUA_TFUNCTION);
	  lua_pushvalue(L,1);	/* make sure it's at the top of the stack */
	  lua_setglobal(L,"myreffunction");
	  return 0;
	}
	
  And to call it:
  
  	static int bar(lua_State *L)
  	{
  	  lua_getglobal(L,"myreffunction");
  	  lua_call(L,0,0);	/* no parameters */
  	  return 0;
  	}
  	
  Another way is to store a reference in the Lua Registry:
  
  	int myfuncref;
  	
  	static int foo(lua_State *L)
  	{
  	  
  	  luaL_checktype(L,1,LUA_TFUNCTION);
  	  myfuncref = luaL_ref(L,LUA_REGISTRYINDEX);
  	  lua_pushinteger(L,myfuncref);
  	  lua_pushvalue(L,1);
  	  lua_settable(L,LUA_REGISTRYINDEX);
  	  return 0;
  	}
  	
  And to call that:
  
  	static int bar(lua_State *L)
  	{
  	  lua_pushinteger(L,myfuncref);
  	  lua_gettable(L,LUA_REGISTRYINDEX);
  	  lua_call(L,0,0);
  	  return 0;
  	}
  	
  Personally, I would store a reference in the Lua Registry as it won't
pollute the global space.

  -spc (This should be enough to get you started)