Lua Error Handling Handling errors in Lua


Example

Assuming we have the following function:

function foo(tab)
  return tab.a
end -- Script execution errors out w/ a stacktrace when tab is not a table

Let's improve it a bit

function foo(tab)
  if type(tab) ~= "table" then
    error("Argument 1 is not a table!", 2)
  end
  return tab.a
end -- This gives us more information, but script will still error out

If we don't want a function to crash a program even in case of an error, it is standard in lua to do the following:

function foo(tab)
    if type(tab) ~= "table" then return nil, "Argument 1 is not a table!" end
    return tab.a
end -- This never crashes the program, but simply returns nil and an error message

Now we have a function that behaves like that, we can do things like this:

if foo(20) then print(foo(20)) end -- prints nothing
result, error = foo(20)
if result then print(result) else log(error) end

And if we DO want the program to crash if something goes wrong, we can still do this:

result, error = foo(20)
if not result then error(error) end

Fortunately we don't even have to write all that every time; lua has a function that does exactly this

result = assert(foo(20))