lua-users home
lua-l archive

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

Just thought it would help others. Below is a macro that creates getter
and setter functions in your class for your lua table vars. Useful if you
have classes in C++ that have a representative table in Lua.

#define LUA_BIND(rettype,func,key,luatype) \
   rettype func(void) { \
      int i = index(); \
      lua_pushstring(state(), key); \
      lua_gettable(state(), (i>=0) ? i : --i); \
      rettype v = lua_to##luatype(state(), -1); \
      lua_pop(state(), 1); \
      return v; \
   } \
   void func(rettype v) { \
      int i = index(); \
      lua_pushstring(state(), key); \
      lua_push##luatype(state(), v); \
      lua_settable(state(), (i>=0) ? i : i-=2); \

rettype is the return type of the function call
func is the binding function name
key is the lua var name of the value you want (assumes its a string)
luatype is the lua type of the value

The macro will call your state() and index() methods that you should have
implemented in your class that return the lua state and index of the table
in the stack.

struct Test{
   lua_State* m_L;
   int m_luaref;
   lua_State* state(void) { return m_L; }
   int index(void) { 
      lua_getref(m_L, m_luaref);
      return -1;
   LUA_BIND(double, age, "age", number);
   LUA_BIND(const char*, name, "name", string);

Some lua table:

  Test = { name = "Sophia", age = 2.5 }

So now you can get and set the members of your table object with

  double age = test.age();

I tried and tried again to abstract my Lua api code behind wrapper classes,
etc... and I'm finding that the Lua api is just so simple to use that its
not necessary. I've resorted to just using simple macors. I congratulate the
Lua team on creating such a fine product!