lua-users home
lua-l archive

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


Is there a way to catch a get/set to a userdata object that is stored in a table? I know how to do it for a global variable, like LHF showed a while back (see example below) -- is there some way to do an equivalent
operation on a table member?

I have a C++/Lua component system, and rather than mirroring all of the get...() and set...() calls of C++ I'd like to make them look like regular table variables and have assignments transparently call the C++ get...() and set...() methods under the hood. So if I had something like this in C++:

struct MyComponent {
   int getValue();
   void setValue (int value);
};


In Lua it would look like:

   MyComponent.value = 22;
   x = MyComponent.value

I got it working by *not* putting anything in the table, catching the "gettable" and "settable" calls and manually looking up the proper table method from an internal array of entry points. It's ugly. Is there a more elegant way to make this happen?

Thanks,
Jason





From:  Luiz Henrique de Figueiredo <lhf@t...>
Date:  Wed May 10, 2000  5:54 pm
Subject:  RE: Direct accessing of application variables from lua


extern int I,J;

 static void getTint(void)
 {
  int* var=(int*) lua_getuserdata(lua_getparam(2));
  lua_pushnumber(*var);
 }

 static void setTint(void)
 {
  int* var=(int*) lua_getuserdata(lua_getparam(2));
  int val=(int) lua_getnumber(lua_getparam(3));
  *var=val;
 }

 void export(void)
 {
  int Tint=lua_newtag();
  lua_pushusertag(&I,Tint);   lua_setglobal("I");
  lua_pushusertag(&J,Tint);   lua_setglobal("J");
  lua_pushcfunction(getTint); lua_settagmethod(Tint,"getglobal");
  lua_pushcfunction(setTint); lua_settagmethod(Tint,"setglobal");
 }