[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: gc problem when using lightuserdata to reference C++ objects
- From: "Duncan Cross" <duncan.cross@...>
- Date: Fri, 14 Nov 2008 12:57:18 +0000
On Fri, Nov 14, 2008 at 12:10 PM, <firstname.lastname@example.org>
Use normal userdata instead of lightuserdata ; associate a
Quoting "Cheng, Long" <email@example.com
> Or is there other
> "proper" ways to handle the objects life cycle? Thanks!
metatable with it, and free memory in the __gc metamethod
(which does not exist for lightuserdata).
You can learn more from :
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.