lua-users home
lua-l archive

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


On Sat, Aug 2, 2014 at 4:38 AM, Marc Balmer <marc@msys.ch> wrote:

> lua_pcall() returns an error before p:close() has been called, the object stays in memory, the connection remains open, and, the printer remains blocked.
>
> For now, as a first solution, we call lua_gc(LUA_GCCOLLECT, ...) after lua_pcall(), but is this an expensive operation?  Is there a better way to handle such objects that hold resources?  Should we only call lua_gc() if lua_pcall() returns an error, or always?
>
> How do others that integrate Lua into C programs deal with such a situation?
>
> Is there a way to mark an object to be immedtiately garbage collected when it is no longer used?

luasocket has a function called socket.newtry() to set a finalizer of
sorts in case an exception is thrown.  This way the connection can be
closed in the event of an exception anyway.  It doesn't sound like
you're using luasocket; you may be using it internally -- but the
concept is the same.  You could do this by defining an error handler
and and using xpcall() instead:
http://www.lua.org/manual/5.2/manual.html#pdf-xpcall

newtry() basically creates an intermediate/temporary function to be
used within socket.try() -- for when the function is actually "run".
You don't have to define a new error handler, you could just
chain-call to the old one, but a step before that might be p:close()