lua-users home
lua-l archive

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


> I just found that the error/pcall/xpcall in lua is just like exceptions, you
> can report a error, and catch it like this:
> 
> function foo()
>    ...
>    if notReady then error"not ready" end
>    ...
> end
> 
> if pcall(foo) then
>   ...
> end
> 
> but I still have some question about this Idiom:
> 
> 1. how can I make sure some operations MUST happen?
> xpcall may be can do this, but the errfunc may not called if f call success.
> some pseudo-code:
> 
> [...]

The name "error function" is not very precise (we changed it to "message
handler" in 5.2). The goal of this parameter to xpcall is not to treat
the error, but to treat the error message (e.g. adding a traceback to
it).

The right place to handle errors is after pcall (or xpcall) returns, as
in your first example:

  if pcall(foo) then
    <error handling code>
  end

So, to make sure that some operations MUST happen just put them out of
the 'if':

  if pcall(foo) then
    <error handling code>
  end
  <MUST happen code>

-- Roberto