lua-users home
lua-l archive

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


I agree, being able to call pcall with the same error function would be useful in any case. As for the thing that I wanted, I gave it more thought and here's an idea I came up with: I think it would be good to implement try,except,finally in a fashion orthogonal to pcall. It won't be as powerful as try,except,finally in other languages, because 'except' won't be able to recover execution. It's pretty much implementation-driven, but first here's the approximate syntax in two cases of interest:

1) Adding additional info to error message:

for i = 1,100 do
  try(function(errorinfo)
    errorinfo.text = tostring(errorinfo.text).."  (i = "..i..")"
  end)
    error("Oops")  -- do something here
  except()  -- 'except' function closes the Try block
end

2) Finally:

local f = assert(io.open("c:/error.txt", "r"))

try(function(errorinfo)
  f:close()
end)
  error(f:read(*a))
finally()

The error handler is passed to try() function and the protected code goes after it as plain code, not as another function (as in case of using pcall for similar goals). try() set up an error handler that would be called in case of an error. except() removes the error handler from handlers list, finally() executes the error handler and removes it. These 2 functions return all arguments they receive, so that one would easily write "return except(5)". The order in which the handlers are executed is the opposite of the order in which they are set up with the pcall error function executing last. I already have an implementation plan, it would be pretty simple. The usage seems relatively convenient, but the syntax is unusual and you must take care of executing except/finally, e.g. if you want to use 'return' inside the first example's Try block, you'll have to turn it into 'return except()'.

--
Best regards,
Sergey Rozhenko                 mailto:sergroj@mail.ru