lua-users home
lua-l archive

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


>Are we going to document lua_boxpointer?

In Lua 5.0 we cleaned up the confusion of what a userdata is and how it is
created: userdata are Lua objects created with lua_newuserdata:

	LUA_API void *lua_newuserdata (lua_State *L, size_t size);

lua_newuserdata creates an object that has an attached buffer of the given
size; this buffer is returned to the host program and can be written to.
Lua never looks inside the buffer, but userdata objects, like all other objects,
are subject to garbage collection. In other words, lua_newuserdata gives
you a buffer that you don't have to worry about mallocing or freeing, but
which you can used to store whatever you want, even dynamically changing its
contents.

lua_boxpointer covers the common case of wanting to store a pointer in this
buffer. lua_unboxpointer gets the pointer from the buffer of the given Lua
object. A typical use is to store the pointer of a C struct that has to be
exported to Lua so that it can have a metatable. Only userdata created with
lua_newuserdata can have metatables. Note also that lua_boxpointer will
return a different Lua object each time it is called, even if the same pointer
is used.

Lua 5.0 also introduced "light" userdata, which are pointers treated as values,
not as objects. Light userdata is more like numbers: no memory is allocated,
except the Lua value struct where all Lua values reside. On the other hand,
"light" userdata cannot have metatables. Two "light" userdata values are the
same iff their pointers are the same.

We think this scheme is clear and makes userdata both flexible and fast.
--lhf