Skip to main content
gamedev.net
🔒 Locked

Lua callback in c++ class

Started by iliak Jan 1, 2007 at 4:17 PM 1 replies 5.5k views
Original Post
iliak
iliak
Hi I needto enumerate ressources in my script (c++ & luabind) :

class cRessourceManager
{
    void  TextureEnum(bool (*func)(const char *));
}

So TextureEnum() need a function like this : bool texenum(const char *name); to be "callbacked". If I'm doing this in my C++ code : TextureEnum(texenum); Everything goes well. Now I want to export it in my lua scripts, so I set a lua function to be the callback but every try fails. I looked at luabind::object but I don't understand the magic behind. Can someone light my fire with a good example plz ?
- Iliak -
[ ArcEngine: An open source .Net gaming framework ]
[ Dungeon Eye: An open source remake of Eye of the Beholder II ]
kwaung
kwaung
Hi, Iliak
I dont use LuaBind. SO I dont know exactly how to do it. But if you want to store pointer to Lua function for call it in your application. You can use luaL_ref() to do the job.
You can write C/C++ function to register Lua function like this.

static int bnd_ResgisterLuaFunction(lua_State *L){  //get parameter  char* pfunc     = (char*)lua_topointer(L,1);  // <Also get some other info like function name, argument count>    // Load the funtion to memory  luaL_loadbuffer(L,func,strlen(func),"LuaFunction");  lua_pop(L,1);  // Store funtion reference  int func_ref = luaL_ref(L, LUA_REGISTRYINDEX);  //<Store all imfomation to callback manager class>  // OK!   return 1;}


When you want to call Lua function that you registerd do something like this.
bool CallbackManager::Call(int func_ref){    // Call lua function by stored Reference   lua_rawgeti(m_pLuaState,LUA_REGISTRYINDEX, func_ref);   if(lua_pcall(LS,0,0,0) != 0)	//<return Error>// OK!return true;   }


You can read more about luaL_ref() here.

http://www.lua.org/pil/27.3.2.html

Hope this help.

Charkrid.

kwaung
kwaung
Ohh, I forgot. Dont forget to call luaL_unref() when you dont need a reference anymore.


Charkrid.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.