lua-users home
lua-l archive

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


On Mon, Jun 28, 2010 at 09:42:50AM -0700, Graham Wakefield wrote:
> This might not be optimal code, but it works for me.

Thank you.
It also works for me and it does what I wanted.
But I must admit, I don't fully understand it.

> /*
> 	get a callback when the value at stack index idx is collected
> */
> static void gc_sentinel(lua_State * L, int idx, lua_CFunction callback) {
> 
> 	lua_pushvalue(L, idx); // value @idx
> 	lua_newuserdata(L, sizeof(void *)); // sentinel userdata
> 		lua_newtable(L);	// userdata metatable with __gc = callback
> 		lua_pushcfunction(L, callback);
> 		lua_setfield(L, -2, "__gc");
> 		lua_setmetatable(L, -2);

That is what was described in the previous mail.
I understand it that far.

But what does the following code do?
I've tried if it still works without it and it does.

> 	/* check for (weak-valued) sentinel table; create if needed */
> 	lua_getfield(L, LUA_REGISTRYINDEX, "__gc_sentinels");
> 	if (lua_isnoneornil(L, -1)) {
> 		lua_pop(L, 1);
> 		lua_newtable(L);
> 		// make weak-keyed
> 		lua_pushstring(L, "v");
> 		lua_setfield(L, -2, "__mode");
> 		lua_pushvalue(L, -1);
> 		lua_setfield(L, -2, "__index");
> 		lua_pushvalue(L, -1);
> 		lua_setmetatable(L, -2);
> 		lua_pushvalue(L, -1);
> 		lua_setfield(L, LUA_REGISTRYINDEX, "__gc_sentinels");
> 	}
> 
> 	lua_insert(L, -3);
> 	lua_insert(L, -2);
> 	lua_settable(L, -3); // lua::sentinel[value @idx] = sentinel userdata
> 	lua_pop(L, 1); // lua::sentinel
> }

May I use your code in a GPLv3+ licensed project?
How would you like to be referred to in the Copyright notice?
Full name with e-mail address?

-- 
AKFoerster