lua-users home
lua-l archive

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


I want to use lua_toclose() to close the state of C structure in the C
stack. For example,

static int
close_foo(lua_State *L) {
  lua_getfield(L, 1, "_ptr");
  struct mystruct *foo = (struct mystruct *)lua_touserdata(L, -1);
  mystruct_exit(foo);
  return 0;
}

int
foobar(lua_State *L) {
  struct mystruct foo;
  mystruct_init(&foo);
  lua_settop(L, 0);

  lua_newtable(L);   // index 1
  lua_pushlightuserdata(L, &foo);
  lua_setfield(L, 1, "_ptr");

  lua_newtable(L);
  lua_pushcfunction(L, close_foo);
  lua_setfield(L, -2, "__close");
  lua_setmetatable(L, 1);

  lua_toclose(L, 1);   // index 1 is a to-be-closed "variable"

  do_something(L, &foo);   // may raise error in this function

  lua_pushnil(L);
  lua_setvalue(L, 1);  // ignore to-be-closed variable 1.

  mystruct_exit(&foo);

   return 0;
}

Is safe to call mystruct_exit(foo) in close_foo ?

>From the source code of lua 5.4, I think it's safe, because calling
foobar is before raising error, the stack of the C function is valid.

 But I'm not sure from the document :

"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."

There is no precise definition of when it will happen (before or after
out of scope).

-- 
http://blog.codingnow.com