lua-users home
lua-l archive

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



On Fri, Nov 14, 2008 at 12:10 PM, <matias.guijarro@free.fr> wrote:
Hi,

Quoting "Cheng, Long" <long.x.cheng@gmail.com>:
> Or is there other
> "proper" ways to handle the objects life cycle? Thanks!
>

Use normal userdata instead of lightuserdata ; associate a
metatable with it, and free memory in the __gc metamethod
(which does not exist for lightuserdata).

You can learn more from :
http://www.lua.org/pil/28.1.html

Cheers,
Matias.

The "full" userdata should be allocated to the size of a pointer, and be used to contain the pointer you'd otherwise be putting straight in as a light userdata, if that isn't obvious:

MyThing* thing = new MyThing();
*((MyThing**)lua_newuserdata(L, sizeof(MyThing*)) = thing;

Light userdata is really just another kind of number value, not a reference-counted object value, and is therefore less useful than it might initially seem. A good use for it is when the external API that you want to bind Lua to can fetch references to things that exist in the Lua universe as a full userdata.

For example, in a 3D engine API you might use a Lua statement to create a 3D object, and later on use an API function that picks the object in the scene that the mouse is pointing at. If you are using the full userdata environment table trick to allow extra properties to be added to the 3D object by redirecting __index and __newindex to the environment table, then these extra properties will be lost if you create a new full userdata containing the pointer that the picking function returns. Instead, when the object is created, you would also add an entry in a special table in the registry, which maps the light userdata to the new 3D object to the full userdata created for it. Later, when the picking function is used, you can use this table to look up the userdata.

-Duncan