lua-users home
lua-l archive

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


On 2018-09-20 22:50, Ivan Krylov wrote:
On Thu, 20 Sep 2018 00:12:21 +0200 nobody <nobody+lua-list@afra-berlin.de> wrote:
From the user code, you call `hopefully( desc, params... )` (could
also be hidden inside some constructor) and if the action fails, that tries the handlers in order (with the stack still intact – so
this is a normal function, no language support needed etc.).

I'm not sure I understand how it's implemented -- can you somehow protect a Lua call in such a way that your handler gets executed at the same place in the stack where the original error() happened? -- but the R language has a similar construct: the tryCatch function.

This doesn't (necessarily) involve pcall/error – just plain call/return.
`hopefully` is just a wrapper that iterates through ways to do the
requested thing, returns the result on success, or throws a real error
when nothing worked.  (And that wrapper just stays in the same place
until it's done, calling functions as it goes.)

A crappy diagram:

  user code
   \- hopefully
       \- default action
       / (reports failure)
       \- handler #1
           \- (does some stuff)
           /
           \- re-tries default action (and succeeds)
        /--/ (passes through the result)
   /---/ (return to user code)

You essentially take the familiar error handling if-then-else, put it in
a function (`hopefully`), and then wrap the code for the different
branches as functions and put those in a list.  This abstracts away a
repeated pattern and at the same time opens it up for later extension.
Internally (hopefully <-> handlers), you can communicate by `nil,errmsg`
or error/pcall (arbitrary choice, doesn't really matter for external
behavior).

-- nobody