[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Struggling with userdata concepts
- From: Michal Kottman <k0mpjut0r@...>
- Date: Sat, 27 Aug 2011 20:03:54 +0200
On 27 August 2011 18:54, Should Pain <pengzhicheng1986@gmail.com> wrote:
> simply saying, you store a C pointer into lua using light userdata, and
> define various operations that can be access from lua as metamethods.
Not entirely true - light userdata are just pointers, nothing else.
They do not have individual metatables, like full userdata have, and
are not garbage collected. Light userdata share a single per-type
metatable (like strings and numbers), so changing it's metatable
changes it globally. To work with light userdata in Lua, you usually
pass them around to functions (like handles).
If you only need to store pointers (allocate the memory yourself, not
in Lua userdata), but want the "full package" (metamethods, gc), you
can store the pointer in Lua full userdata, i.e.:
foo **ud = (foo**) lua_newuserdata(L, sizeof(foo*));
*ud = ptr; /* store the pointer inside the userdata */
To later get the stored pointer, you can do this:
foo *ptr = *(foo**) luaL_checkudata(L, index, metatable_name);