[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Light User Data
- From: Edgar Toernig <froese@...>
- Date: Thu, 05 Sep 2002 03:46:39 +0200
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:
<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
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.
Obbug: int and longs are not save to store in floats, too...