Latest web development tutorials

Lua Error Handling

Program run error handling is necessary, in our file operations, data transfer and web service invocation will appear in unexpected errors. If you do not pay attention to deal with error messages, according to the information will leak, can not run and so on.

Any programming languages, error handling is required. Error types are:

  • Grammatical errors
  • Runtime Error

Grammatical errors

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

-- test.lua 文件
a == 2

The above code is executed as a result of:

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

As you can see, there have been more than a syntax error, a "=" sign followed by two "=" sign is different. A "=" is the assignment expression two "=" is the comparison operation.

Another example:

for a= 1,10

The above program will appear the following errors:

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

Syntax errors is easier than running a program error, run error unable to locate the specific errors, grammatical mistakes that we can quickly resolve, such as the above examples as long as we do in the for statement can be added:

for a= 1,10

Runtime Error

Run the program can perform error is normal, but it will output an error message. The following examples because the parameters input errors, program execution error:

function add(a,b)
   return a+b


When we compile and run the following code, the compiler can be successful, but at run time will produce the following error:

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 because the program lacks the b parameter.

Error Handling

We can use two functions: assert and error to handle errors. Examples are as follows:

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

The above program will appear the following errors:

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 ?

Example assert first checks the first argument, if no problem, assert does nothing; otherwise, the second argument as to assert error message thrown.

error function


error (message [, level])

: Terminates the function being executed, and returns the contents of the message as the error message (error function will never return)

Typically, error will be some additional information about the error message to the head position.

Level parameter indicates the position to get wrong:

  • Level = 1 [default]: To call error (file + line number)
  • Level = 2: function which calls the error function indicated
  • Level = 0: do not add error location

pcall and xpcall, debug

Lua error handling, you can use the function pcall (protected call) to wrap the code to be executed.

pcall receiving a function and you want to pass a parameter of the latter, and executed, the result: there is an error, no error; or the return value of true or false, errorinfo.

Syntax is as follows

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

Simple example:

> =pcall(function(i) print(i) end, 33)
> =pcall(function(i) print(i) error('error..') end, 33)
false        stdin:1: error..
> function f() return false,2 end
> if f() then print '1' else print '0' end

pcall in a "protected mode" to call the first argument, therefore pcall capture function can perform any errors.

Typically when an error occurs, it is hoping to end up with more debugging information, not just where the error occurred. But pcall returns, it has destroyed part of the contents of the call Zhan.

Lua provides xpcall function, xpcall receiving a second parameter - an error handler when an error occurs, Lua error handler will be called before calling Zhan show to see (unwind), then you can use this function in debug library to obtain additional information about the error.

debug library provides two generic error handler:

  • debug.debug: Lua provide a prompt, allowing users to spread the wrong reasons
  • debug.traceback: According to Zhan call to build an extended error message
> = Xpcall (function (i) print (i) error ( 'error ..') end, function () print (debug.traceback ()) end, 33) 33 stack traceback: stdin: 1: in function [C]: in function 'error' stdin: 1: in function [C]: in function 'xpcall' stdin: 1: in main chunk [C]:? In false nil

xpcall Example 2:

function myfunction ()
   n = n/nil

function myerrorhandler( err )
   print( "ERROR:", err )

status = xpcall( myfunction, myerrorhandler )
print( status)

The above program will appear the following errors:

ERROR:	test2.lua:2: attempt to perform arithmetic on global 'n' (a nil value)