Am 08.09.2014 um 10:31 schröbte Procházka Lukáš Ing. - Pontex s. r. o.:
Hello,
Hi!
I'm trying to understand Lunar<T> code.
In case anyone else is interested, the Lunar source code is here[1] ...
There is still one point I can't understand:
---
static int push(lua_State *L, T *obj, bool gc=false) {
if (!obj) { lua_pushnil(L); return 0; }
luaL_getmetatable(L, T::className); // lookup metatable in Lua
registry
if (lua_isnil(L, -1)) luaL_error(L, "%s missing metatable",
T::className);*/
int mt = lua_gettop(L);
subtable(L, mt, "userdata", "v"); // WHY THIS???
...
---
Lunar creates a metatable for each T; that's clear.
(
This metatable has also subtable named "do not trash", which contains
keys=userdata for userdata which are to be ignored during GC cycle;
keys in "do not trash" table are weak; obviously.
)
But - why is there a subtable "userdata" with weak values?
It seems to me it is not used anywhere later, so why?
It is used later in the `pushuserdata` function to map pointers to
objects (as lightuserdata) to full userdata wrapping those object
pointers. This way you can reuse the full userdata and avoid memory
allocation if a suitable full userdata already exists in the Lua state.
The table is weak-valued so that it doesn't prevent the full userdata
from being garbage collected if it isn't referenced anywhere else.
HTH,
Philipp
[1]: http://lua-users.org/wiki/CppBindingWithLunar