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;
> }

  Okay, I removed the call to lua_remove() and that cleared up the error
message.  I then added a call to printf() in the close() function and did
the the following Lua code:

	do
	  local x = require "toclose"
	  print(x)
	end

  The output I got was:

	CLOSING!
	table: 0x949aa70

  Going back to the manual:

	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.

		(emphasis added)

  So that explains "CLOSING" being printed before variable x being printed.
It also seems that once a variable is marked "toclose" on the stack in C,
then one should not shift it about via lua_remove() (and possibly
lua_insert()).  It's looking like the manual should clarify aspects of
toclose variables on the C side of things.

  -spc