lua-users home
lua-l archive

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


Hello!
 
This is my fist post on this message board :)
 
I use Lua and toLua an I have created a class that have this 2 functions:
///////////////////////////////////////////////////////////////////////////////
// Name:  RegisterClass
// Description: Register en C++ class that Lua can see.
//
bool ZFScript::ExposeClass(char *szName, lua_CFunction o_LuaGet, 
                           lua_CFunction o_LuaSet)
{
 // check if type is already registered
 bool bAlreadyExist = true;
 if(m_kExposedClasses.find(string(szName)) == m_kExposedClasses.end())
  bAlreadyExist = false;
 
 if(bAlreadyExist)
 {
  printf("SCRIPT_API: Class [%s] already exposed %s\n", szName);
  return true;
 }
 
 // Create Lua tag for Test type.
 lua_pushcfunction(m_pkLua, o_LuaGet);
 lua_settagmethod(m_pkLua, tolua_tag(m_pkLua,szName), "getglobal");
 
 lua_pushcfunction(m_pkLua, o_LuaSet);
 lua_settagmethod(m_pkLua, tolua_tag(m_pkLua,szName), "setglobal");
 
 m_kExposedClasses.insert(string(szName));
 return true;
}
 
///////////////////////////////////////////////////////////////////////////////
// Name:  ExposeClass
// Description: Register a C++ object that Lua kan se.
//
bool ZFScript::ExposeObject(const char* szName, void* pkData, char* szClassName)
{
 lua_pushusertag(m_pkLua, pkData, tolua_tag(m_pkLua, szClassName));
 lua_setglobal(m_pkLua, szName);
 return true;
}
 
The problem is that I must have 2 static functions in every class that I want to expose to Lua.
class Foo
{
...
  
static int LuaSet(lua_State* pkLua)
  {
   Foo* var=(Foo*) lua_touserdata(pkLua,2);
   Foo* val=(Foo*) lua_touserdata(pkLua,3);
   var=val;
   return 0;
  }
 
  static int LuaGet(lua_State* pkLua)
  {
   Foo* var=(BasicConsole*) lua_touserdata(pkLua,2);
   lua_pushusertag(pkLua, var, tolua_tag(pkLua, "Foo"));
   return 1;
  }
 
...
 
};
 
Because I expose my classes and objects like this:
 m_pkScript = new GameScript(); // GameScript inherit public by ZFScript
 m_pkScript->ExposeClass("Foo", Foo::LuaGet, Foo::LuaSet);
 m_pkScript->ExposeObject("pkFoo", pkFoo, "Foo");
 
Is there a better solution? This is not a very nice way to do it...
 
Thanks! /Erik.