Lua error handling


Error handling is necessary during program operation. Unexpected errors will occur during file operations, data transfer and web service calls. If you do not pay attention to the handling of error messages, information will be leaked and the program will not run.

In any programming language, error handling is required. Error types are:

  • Syntax error

  • Running error


Syntax error

Syntax errors are usually caused by improper use of program components (such as operators, expressions). A simple example is as follows:

-- test.lua 文件
a == 2

The execution result of the above code is:

lua: test.lua:2: syntax error near '=='

As you can see, there is a syntax error in the above, one "=" followed by two "=" There is a difference in number. One "=" is an assignment expression and two "=" are comparison operations.

Another example:

for a= 1,10
   print(a)
end

The following error will occur when executing the above program:

lua: test2.lua:2: 'do' expected near 'print'

Syntax errors are simpler than program running errors. Running errors cannot locate specific errors, and syntax errors We can solve the error quickly. For example, in the above example, we only need to add do under the for statement:

for a= 1,10
do
   print(a)
end

Running error

Running error means that the program can be executed normally, but it will Output error message. In the following example, due to incorrect parameter input, an error occurs during program execution:

function add(a,b)
   return a+b
end

add(10)

When we compile and run the following code, the compilation can be successful, but the following error will occur during operation:

lua: test2.lua:2: attempt to perform arithmetic on local 'b' (a nil value)
stack traceback:
	test2.lua:2: in function 'add'
	test2.lua:5: in main chunk
	[C]: ?

The following error message is caused by the program missing the b parameter.


Error handling

We can use two functions: assert and error to handle errors. The example is as follows:

local function add(a,b)
   assert(type(a) == "number", "a 不是一个数字")
   assert(type(b) == "number", "b 不是一个数字")
   return a+b
end
add(10)

The following error will occur when executing the above program:

lua: test.lua:3: b 不是一个数字
stack traceback:
	[C]: in function 'assert'
	test.lua:3: in local 'add'
	test.lua:6: in main chunk
	[C]: in ?

In the example, assert first checks the first parameter. If there is no problem, assert does not do anything; otherwise, assert starts with the first parameter. The two parameters are thrown as error messages.

error function

Syntax format:

error (message [, level])

Function: Terminate the executing function and return the content of the message as the error message (the error function will never return)

Normally, error will append some error location information to the message header.

The Level parameter indicates the location where the error was obtained:

  • Level=1[default]: is the calling error location (file + line number)

  • Level=2: Indicate which function calls the error function

  • Level=0: Do not add error location information


pcall and xpcall, debug

To handle errors in Lua, you can use the function pcall (protected call) to wrap the code that needs to be executed.

pcall receives a function and the parameter of the latter to be passed, and executes it. The execution result is: error or no error; the return value is true or false, errorinfo.

The syntax format is as follows

if pcall(function_name, ….) then
-- 没有错误
else
-- 一些错误
end

Simple example:

> =pcall(function(i) print(i) end, 33)
33
true
   
> =pcall(function(i) print(i) error('error..') end, 33)
33
false        stdin:1: error..
<pHere, pay attention to the logical judgment of the return value:< p="">
> function f() return false,2 end
> if f() then print '1' else print '0' end
0

pcall in a "Protected mode" to call with first argument, so pcall can catch any errors in function execution.

Usually when an error occurs, you want to get more debugging information, not just the location where the error occurred. But when pcall returns, it has destroyed part of the calling stack.

Lua provides the xpcall function. xpcall receives the second parameter - an error handling function. When an error occurs, Lua will call the error handling function before calling unwind, so it can be The debug library is used in this function to obtain additional information about the error.

The debug library provides two general error handling functions:


  • debug.debug: Provides a Lua prompt to allow users to find out the cause of spread errors

  • debug.traceback: Construct an extended error message based on the callback

>=xpcall(function(i) print(i) error( 'error..') end, function() print(debug.traceback()) end, 33) 33 stack traceback: stdin:1: in function