lua-users home
lua-l archive

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


Evan Wies wrote:
> 
> I am trying to understand the right way to use the light userdata
> (in Lua 5 of course).
> 
> As I understand it, light userdata is just a pointer value and has no
> metatable (since it's light) and tag (since it's Lua 5).

Right.  Like numbers.  In fact, formerly, numbers were used to store
C-pointers but it's not save to store pointers in floats.  So the
light userdata was added as a way to store C-pointers within Lua.

You need them any time you want to:

 - map C-pointers to a Lua object.  I.e. you use the registry
   as the mapping table: KEY is the light userdata with your
   C-pointer and VALUE is the corresponding Lua object:

     create mapping:
	lua_pushlightuserdata(L, <c-pointer>);
        lua_pushvalue(L, <index-of-lua-object>);
        lua_rawset(L, LUA_REGISTRYINDEX);

     fetch object:
        lua_pushlightuserdata(L, <c-pointer>);
        lua_rawget(L, LUA_REGISTRYINDEX);
        <object on stack>

 - pass C-pointers to functions called from Lua.  You push your
   pointer as a light userdata and attach that as an upvalue to
   your function.

      create function:
        lua_pushlightuserdata(L, <c-pointer>);
        lua_pushcclosure(L, <function>, 1);
        <function on stack>

      fetch within function:
        void *handle = lua_touserdata(L, lua_upvalueindex(1));


> But, since it lacks any tags, how are you supposed to do
> anything typesafe with this value?

Make sure that you cannot get the wrong type ;-)

<b>As a rule: never export light userdata to Lua scripts!</b>

Use them within your C code and never make them visible outside of
your module.  If you do, a Lua script may bomb your system.

Ciao, ET.


Obbug: int and longs are not save to store in floats, too...