lua-users home
lua-l archive

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


This might not be optimal code, but it works for me.

/*
	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);

	/* 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
}

int luaclose_mymodule(lua_State * L) {

	// your module cleanup code

}

int luaopen_mymodule(lua_State * L) {

	// your module initialization code

	gc_sentinel(L, -1, luaclose_mymodule);
	return 1;
}

On Jun 24, 2010, at 7:25 AM, Mailing-Listen wrote:

> On Wed, Jun 23, 2010 at 09:31:21PM +0200, Mailing-Listen wrote:
>> On Wed, Jun 23, 2010 at 10:17:16PM +0300, M Joonas Pihlaja wrote:
>>> 
>>>> Then I wanted to compile the language binding as a module. That works fine as 
>>>> long as it runs. But I have the problem, that I don't know how to do the 
>>>> cleanup afterwards.
>>> 
>>> When your module is opened for the first time you can store a userdata 
>>> in the registry and set the userdata's __gc metamethod to do whatever 
>>> cleanup you need.  When the lua_State is being destroyed your cleanup 
>>> function will be executed before your module is unloaded by Lua.
>> 
>> That sounds like it is what I was looking for. I admit that I am not
>> that deep into lua, yet. But I'm definitely going to have a look at it.
> 
> Well, it's harder than I thought.
> But I keep it on my TODO list... :-\
> 
> -- 
> AKFoerster