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

Error handling in Lua

Started by Mads, 27 January 2013 - 08:06 PM
Mads #1
Posted 27 January 2013 - 09:06 PM
Normally when an error occurs in an application, we get a big red error message. But what if we want to continue, and "not care" about the errors? That's when error handling comes in handy!

You usually see error handling done with the function pcall(). This function provides a boolean status.

If this value is false, the function encountered an error, and pcall() will return any datatype as it's second return value. That is the information provided by error().

If status is true, it will just return the return values of the function called via pcall().

This is an example of error handling with pcall:


local function foo(x, y)
	return tostring(x) + y
end

local v2 = "hello"

local status, p2 = pcall(foo, 4, v2)

print(not status and "Error while running foo(): " .. tostring(p2) or "foo() returned value: " .. p2)

This code will print "Error while running foo(): attempt to perform artihmetic on string".

Now, if we change v2 to a number, we will see a different result. If we use this code instead:


local function foo(x, y)
	return tostring(x) + y
end

local v2 = 5

local status, p2 = pcall(foo, 4, v2)

print(not status and "Error while running foo(): " .. tostring(p2) or "foo() returned value: " .. p2)

We will see, that the program prints "foo() returned value: 9", because 4 + 5 = 9.


You might have noticed, that I do

pcall(foo, 4, v2)
instead of

pcall(foo(4, v2))

That if because the latter will run the function, and foo will expect the return value of foo() to be the function to run.
Instead I pass in the function name, and then the arguments.
shiphorns #2
Posted 30 January 2013 - 07:34 PM
Interesting. I'm definitely going to look into thei further. I was wondering if Lua had anything remotely similar to try..catch..finally, and this seems to be the only thing even close.