lua-users home
lua-l archive

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


AFAIK you can do ADA's like error handling in lua.

function fly(from,to)
   --- ...
    error("motor blown")
   --- ...
    error("radio failure")
   --- ...
    error("sabotage occurred")
end

status, problem = pcall(fly,"MEX","MAD");

if  status then
   print("welcome to madrid!")
else
   if problem == "motor blown" then
      print("repair motor")
   elseif problem == "radiu failure"
      print("try another channel")
   else
      print("PANIC")
   end
end


other than that you can use xpcall in lua (which unfortunatelly
doesn't allow you to pass any arguments (even one would help) ) and
set an error handler.

function mex_mad()
  fly("MEX","MAD")
end

function handle_problem(problem)
   if problem == "motor blown" then
      print("repair motor")
   elseif problem == "radiu failure"
      print("try another channel")
   else
      print("PANIC")
   end
end

xpcall(mex_mad,handle_problem)

-- wordy not realy unelegant

BTW it would be nice if there was syntactical sugar to do this like

try
   fly("MEX","MAD");
catch "motor blown"
  --xxx
catch ""
 --yyy
catch
 --zzz
end

in C lua_pcall allows you to set a handler It would be nice If
userdata could be passed as an error I agree but I think accurate
error reporting can do that.

int err_hdl(lua_State* L) {
  const char* err  = lua_tostring(L,1);
  if (*err == '!') {
      /* our error */
  } else {
    /* someone else's */
  }

   return 0;
}


On 2/16/06, Chris <coderight@gmail.com> wrote:
> What is the proper way to do real error handling in Lua?
>
>  Currently I see the error(msg) call and checking return values from
> functions.
>
>  error() is too limited because you can not programmatically tell what
> happened.  All you can return is a string.  This is fine for interactive
> stuff but not so good when you need your program to take special actions
> when certain errors occur
>
>  The only other choice I know of is to return error codes from every
> function.  This is extremely annoying and almost destroys the point of using
> a scripting language in the first place.  Then you start having to worry
> about both returned error codes and catching errors returned via error() and
> makes the code ugly.
>
>  I'm thinking what would be nice is if error() (and the C versions like
> lua_error) could return more than just a text message.   Or some sort of
> exception mechanism. Or...  Is anything like that possible?
>
>  --
>  // Chris
>


--
This information is top security. When you have read it, destroy yourself.
-- Marshall McLuhan