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 ?

What do you mean by "safe"? What is exactly your concerns?

(A detail in your code: you do not need the last three calls [pushnil,
setvalue, mystruct_exit]. If you do not set nil, when you return
Lua will call close_foo and then mystruct_exit for you.)

-- Roberto