lua-users home
lua-l archive

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


Am 16.11.2015 um 16:46 schröbte Viacheslav Usov:
On Mon, Nov 16, 2015 at 3:11 PM, Philipp Janda <siffiejoe@gmx.net> wrote:

If Lua had a hook that is called whenever an error is about to be thrown,
you could do something like the following:

xpcall/pcall are basically such a hook. The real issue is not having those
hooks; it is that their use results in a program that is not elegant (and
usually quite arcane), which no one enjoys writing (the previously cited
LuaSQL example is a case in point). For example, consider this part in your
code:

       local a, b, c
       local cleanup = on_error( function()
         if c then c:destroy() end
         if b then b:clear() end
         if a then a:close() end
       end )
       a = f()
       b = a:foo()
       c = b:bar()

It violates quite blatantly the usual wisdom in Lua that one initializes
locals right in the their declaration, not six feet lines under. And it
forces the user to do what the compiler/runtime could do much better: track
what has been finalized and what has not.

What about:

    local t = transaction( function( a, b, c )
      if c then c:destroy() end
      if b then b:clear() end
      if a then a:close() end
    end )
    local a = t( f() )
    local b = t( a:foo() )
    local c = t( b:bar() )
    -- do something with a, b, c
    -- ...
    t:commit() -- or t:rollback(), or t:cleanup()

No locals declared before initialization, and you could provide a default rollback function that invokes `__gc` metamethods on all stored values (although I find that rather ugly and unsafe).


Cheers,
V.


Philipp