This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Ponder's profile picture

Error Handling

Started by Ponder, 15 July 2012 - 04:55 PM
Ponder #1
Posted 15 July 2012 - 06:55 PM
Is there a convinient way for error handling in Lua?

I read about error () and pcall () in the Lua Doc, but that doesn't get me anywhere actually, since pcall only returns a bolean wheather the function given produced an error or not and error () apparently is only able to raise errors.

The problem with pcall is that apparently I have no way to access any return values of the given function. E.g.:

function foo (x)
  return x.value * 42
end

-- this returns only true or false, but I'd rather have x.value * 42 and still being able to catch any errors in case bar is not a table
bar = {value = 1}
retvar = pcall (foo, bar)
MysticT #2
Posted 15 July 2012 - 08:20 PM
From the lua manual:
Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error message.
So just do:

local ok, val = someFunction()
if ok then
  print(val)
else
  print("Error")
end
Ponder #3
Posted 15 July 2012 - 08:53 PM
Oh, my bad then. Should've read more closely. Thanks. :S
Orwell #4
Posted 15 July 2012 - 09:08 PM
From the lua manual:
Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error message.
So just do:

local ok, val = someFunction()
if ok then
  print(val)
else
  print("Error")
end

I guess you ment:

local ok,val = pcall(someFunction())
:P/>/>
MysticT #5
Posted 15 July 2012 - 09:26 PM
I guess you ment:

local ok,val = pcall(someFunction())
;)/>/>
My bad :P/>/>
Actually, it would be:

local ok, val = pcall(someFunction)
you don't have to call the function, just pass it as a parameter.
But I think he gets the point :)/>/>
Ponder #6
Posted 15 July 2012 - 10:32 PM
Yup, I noticed that. :P/>/>
Orwell #7
Posted 15 July 2012 - 11:13 PM
I guess you ment:

local ok,val = pcall(someFunction())
;)/>/>
My bad :P/>/>
Actually, it would be:

local ok, val = pcall(someFunction)
you don't have to call the function, just pass it as a parameter.
But I think he gets the point :)/>/>

Haha, now I make a mistake myself O.o =P