lua-users home
lua-l archive

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


Hello,
Luiz Henrique de Figueiredo wrote:

You can "box" them inside a heavy userdata. C pointers that do not need GC
methods can be stored in light userdata.

For discussions of heavy x light userdata, search the lua-l archives for
lua_newuserdata. For instance:
  http://lua-users.org/lists/lua-l/2002-11/msg00062.html
  http://lua-users.org/lists/lua-l/2002-08/msg00162.html
After last discussion about boxing pointers I have wrote function to emulate old lua-4 behavior (lua_pushuserdata). It's based on your proposal about using weak tables and it was pretty easy to implement :-)

This function makes possible box the same pointer twice (or more) and then compare it from lua. If you assign metatable with __gc function you are able to use GC for any C data..

#define bos_unbox lua_unboxpointer
void bos_box(lua_State *L, void *data)
{
   lua_pushstring(L,"BOXER");            /* "BOXER" */
   lua_rawget(L,LUA_REGISTRYINDEX);      /*  BOXER? */
   if(lua_isnil(L,-1)) {
       lua_remove(L,-1);
       lua_newtable(L);                  /* {} */

       /* lua_setmode(L,-1, "kv"); */
       {
           lua_newtable(L);              /* {} meta */
           lua_pushstring(L, "__mode");  /* {} meta "__mode" */
           lua_pushstring(L, "kv");      /* {} meta "__mode" "kv" */
	    lua_settable(L, -3);          /* {} meta */
           lua_setmetatable(L,-2);       /* {} */
       }
lua_pushliteral(L,"BOXER");
       lua_pushvalue(L,-2);
       lua_settable(L,LUA_REGISTRYINDEX);
   }
lua_pushlightuserdata(L,data); /* BOXER, data */
   lua_gettable(L,-2);                   /* BOXER, udata? */
   if(lua_isnil(L,-1)) {
       lua_remove(L,-1);
       lua_boxpointer(L,data);           /* BOXER, udata */

       lua_pushlightuserdata(L,data);    /* BOXER, udata, data */
       lua_pushvalue(L, -2);             /* BOXER, udata, data, udata */
       lua_settable(L,-4);               /* BOXER, udata */
   }

   lua_remove(L,-2);                     /* udata */
}


Best Regards,
Andrzej Borsuk

ps.
Last time I was wrote that lua sollution is very limited, I was wrong! After some looking into Lua sources, I have changed my mind. Current Lua sollution is very clean and simple -- its much better than prevoius.

--
    _
   (;[   SPAM?
  \/>)   Proszę wysyłać na moje podstawowe konto
 `ab~^   mailto:root@localhost