Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Lua error handling


May 12, 2021 Lua


Table of contents


Lua error handling

Error handling in program operation is necessary, and unforced errors occur during file operations, data transfer, and web service calls. If you do not pay attention to the processing of error messages, it will result in information leakage, programs can not run and so on.

Error handling is required in any program language. The types of errors are:

  • The syntax is wrong
  • The error was run

The syntax is wrong

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

-- test.lua 文件
a == 2

The above code execution results are:

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

As you can see, there is a syntax error above, and there is a difference between one """" sign and two "" A """ is an assignment expression and two """" is a comparison operation.

Another example:

for a= 1,10
   print(a)
end

The following error occurs when the above procedure is performed:

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

Syntax errors are simpler than program run errors, run errors cannot locate specific errors, and syntax errors can be resolved quickly, such as the above example we just add do under the for statement:

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

The error was run

A running error is that the program can execute normally, but an error message is output. The following examples are incorrectly executed due to incorrect parameter input:

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

add(10)

When we compile and run the following code, the compilation is successful, but it produces the following errors when it runs:

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 information is due to the program missing the b parameter.


Error handling

We can use two functions: assert and error to handle errors. Here's an example:

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

The following error occurs when the above procedure is performed:

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 instance, the assert first checks the first argument and, if there is no problem, the assert does nothing;

The error function

Grammar format:

error (message [, level])

Function: Terminates the function being executed and returns the contents of the mesage as an error message (the error function never returns)

Typically, error attachs some information about the wrong location to the message header.

The Level parameter indicates where to get the error:

  • Level-1 (default): for calling the error location (file-line number)
  • Level=2: Indicates which function calls the error function
  • Level=0: No incorrect location information is added

pcall and xpcall, debug

To handle errors in Lua, you can wrap the code that needs to be executed using the function pcall .

pcall receives a function and wants to pass an argument of the latter, and executes the result: error-free, error-free;

The syntax format is as follows

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

A 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..
> function f() return false,2 end
> if f() then print '1' else print '0' end
0

the pcall calls the first argument in a "protection mode", so the pcall can catch any errors in function execution.

Often, when an error occurs, you want to drop more debugging information than just where the error occurred. Buthen Pcall Returns, IT Has Destroyed Parts of The 桟 The Call.

Lua provides the xpcall function, in which xpcall receives the second argument, an error handler, and when an error occurs, Lua calls the error handler before callingZhanShow, so you can use the debug library in this function to get additional information about theError.

The debug library provides two common error handling functions:

  • debug.debug: Provides a Lua prompt that lets the user reason for the spread error
  • Debug.traceback: build an 桟 error message based on the call
>=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 ? f alse nil

xpcall uses instance 2:

function myfunction ()
   n = n/nil
end

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

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

The following error occurs when the above procedure is performed:

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