lua-users home
lua-l archive

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


It was thus said that the Great actboy168 once stated:
> #include <lua.h>
> #include <lauxlib.h>
> 
> static int close(lua_State *L) {
>   return 0;
> }
> 
> static void newtable(lua_State *L) {
>     static const luaL_Reg mt[] = {
>         {"__close", close},
>         {NULL, NULL}
>     };
>     lua_newtable(L);
>     luaL_newlib(L, mt);
>     lua_setmetatable(L, -2);
> }
> 
> int luaopen_toclose(lua_State *L) {
>     lua_pushinteger(L, 1);
>     newtable(L);
>     lua_toclose(L, -1);
>     lua_remove(L, -2); // throw error: attempt to close non-closable
> variable '?'
>     return 1;
> }

So the flow is:

	lua_pushinteger(L,1);	// int
	lua_newtable(L):	// table int
	luaL_newlib(L,mt);	// table table int
	lua_setmetatable(L,-2);	// table int
	lua_toclose(L,-1);	// table int
	lua_remove(L,-2);	// table

  The manual states for lua_toclose():

	... the value at that index in the stack will be closed when it goes
	out of scope. Here, in the context of a C function, to go out of
	scope means that the running function returns to Lua, there is an
	error, or the index is removed from the stack through lua_settop or
	lua_pop. An index marked as to-be-closed should not be removed from
	the stack by any other function in the API except lua_settop or
	lua_pop.

	This function should not be called for an index that is equal to or
	below an already marked to-be-closed index.

  Hmm ... the code seems like it should work.  Try commenting out the
lua_remove() and see if it works. It might be that moving the item to be
cleaned is disallowed as well and the manual doesn't mention it.

  -spc