Error in error handling lua

Lua — Error Handling Complete Python Prime Pack for 2023 9 Courses 2 eBooks Artificial Intelligence & Machine Learning Prime Pack 6 Courses 1 eBooks Java Prime Pack 2023 8 Courses 2 eBooks Need for Error Handling Error handling is quite critical since real-world operations often require the use of complex operations, which includes […]

Содержание

  1. Lua — Error Handling
  2. Complete Python Prime Pack for 2023
  3. Artificial Intelligence & Machine Learning Prime Pack
  4. Java Prime Pack 2023
  5. Need for Error Handling
  6. Syntax Errors
  7. Run Time Errors
  8. Assert and Error Functions
  9. pcall and xpcall
  10. Error in error handling lua
  11. 8.4 – Error Handling and Exceptions
  12. Programmer Group
  13. Error handling in lua learning
  14. error handling
  15. dynamic link
  16. error
  17. Error handling and exceptions
  18. Error messages and traceability
  19. Two general processing functions of debug library
  20. Periodic «Lua: error in error handling» crashes #3011
  21. Comments
  22. Error in error handling lua
  23. 8.5 – Error Messages and Tracebacks

Lua — Error Handling

Complete Python Prime Pack for 2023

9 Courses 2 eBooks

Artificial Intelligence & Machine Learning Prime Pack

6 Courses 1 eBooks

Java Prime Pack 2023

8 Courses 2 eBooks

Need for Error Handling

Error handling is quite critical since real-world operations often require the use of complex operations, which includes file operations, database transactions and web service calls.

In any programming, there is always a requirement for error handling. Errors can be of two types which includes,

  • Syntax errors
  • Run time errors

Syntax Errors

Syntax errors occur due to improper use of various program components like operators and expressions. A simple example for syntax error is shown below.

As you know, there is a difference between the use of a single «equal to» and double «equal to». Using one instead of the other can lead to an error. One «equal to» refers to assignment while a double «equal to» refers to comparison. Similarly, we have expressions and functions having their predefined ways of implementation.

Another example for syntax error is shown below −

When we run the above program, we will get the following output −

Syntax errors are much easier to handle than run time errors since, the Lua interpreter locates the error more clearly than in case of runtime error. From the above error, we can know easily that adding a do statement before print statement is required as per the Lua structure.

Run Time Errors

In case of runtime errors, the program executes successfully, but it can result in runtime errors due to mistakes in input or mishandled functions. A simple example to show run time error is shown below.

When we build the program, it will build successfully and run. Once it runs, shows a run time error.

This is a runtime error, which had occurred due to not passing two variables. The b parameter is expected and here it is nil and produces an error.

Assert and Error Functions

In order to handle errors, we often use two functions − assert and error. A simple example is shown below.

When we run the above program, we will get the following error output.

The error (message [, level]) terminates the last protected function called and returns message as the error message. This function error never returns. Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

pcall and xpcall

In Lua programming, in order to avoid throwing these errors and handling errors, we need to use the functions pcall or xpcall.

The pcall (f, arg1, . ) function calls the requested function in protected mode. If some error occurs in function f, it does not throw an error. It just returns the status of error. A simple example using pcall is shown below.

When we run the above program, we will get the following output.

The xpcall (f, err) function calls the requested function and also sets the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code.

A simple example for xpcall is shown below.

When we run the above program, we will get the following output.

As a programmer, it is most important to ensure that you take care of proper error handling in the programs you write. Using error handling can ensure that unexpected conditions beyond the boundary conditions are handled without disturbing the user of the program.

Источник

Error in error handling lua

This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.

8.4 – Error Handling and Exceptions

For many applications, you do not need to do any error handling in Lua. Usually, the application program does this handling. All Lua activities start from a call by the application, usually asking Lua to run a chunk. If there is any error, this call returns an error code and the application can take appropriate actions. In the case of the stand-alone interpreter, its main loop just prints the error message and continues showing the prompt and running the commands.

If you need to handle errors in Lua, you should use the pcall function (protected call) to encapsulate your code.

Suppose you want to run a piece of Lua code and to catch any error raised while running that code. Your first step is to encapsulate that piece of code in a function; let us call it foo : Then, you call foo with pcall : Of course, you can call pcall with an anonymous function:

The pcall function calls its first argument in protected mode, so that it catches any errors while the function is running. If there are no errors, pcall returns true , plus any values returned by the call. Otherwise, it returns false , plus the error message.

Источник

Programmer Group

A programming skills sharing group

Error handling in lua learning

error handling

dynamic link

In Lua, dynamic links are considered the parent of all other mechanisms

So you can use it to dynamically load any other mechanism not in Lua

Two parameters required for package.loadlib

  1. Full path to the library
  2. Correct function name

The loadlib function loads the specified library and links it into Lua

It does not call any functions in the library

Instead, a function written in C is returned as a Lua function

If an error occurs while loading the library or looking for the initialization function, nil and an error message are returned

  1. Usually use require to load the C library. This function will search the specified library
  2. Then load the library with loadlib and return the initialization function
  3. This initialization function should register the functions provided in the library with Lua, just like other functions defined in the Lua code block

error

Lua is an extension language, usually embedded in applications

If we crash or exit directly when an error occurs, we can’t capture where the error occurred

So whenever Lua has an error, it should end the current block and return to the application

Any unexpected condition in Lua causes an error, such as:

  1. Add two non numeric values
  2. Call on a value that is not a function
  3. Index a value that is not a Table

You can explicitly raise an error by calling the error function

  1. Function that needs to pass in an error message
  1. assert returns the first parameter if it is true
  2. If the first parameter is false or nil, an error will be raised
  3. The second parameter is an optional information string
  4. Its parameters are evaluated when assert is called
  5. In the following code, Lua will connect strings even if n is a numeric type

When a function encounters an unexpected situation, i.e. «exception», two basic behaviors can be taken

  1. Return error code (usually nil)
  2. Raise an error (call error)

sin passes in table as a parameter

Usually neither the parameters nor the return value of sin are checked

You can stop the calculation and give an error message

Non existence of io.open file or abnormal behavior when access is denied

Whether a file exists or not can be verified by whether it can be opened

When io.open is unable to open a file, nil should be returned with an error message attached

Error handling and exceptions

In most cases, you don’t need to do any error handling in Lua, which is the responsibility of the application calling Lua

Because all Lua activities start with a single call from the application

  1. Lua is usually required to execute a block
  2. If an error occurs, the call returns the error code and is processed by the application

When an error occurs in the interpreter program, the main loop prints the error message, then continues to display the prompt and waits for subsequent commands to be executed

When handling errors in Lua, pcall must be used to wrap the code to be executed. P > means protect

pcall can catch any errors raised when a function executes

  1. If there are no errors, it will return true and the return value of the function call
  2. If there is an error, it will return false and error message

An anonymous function can be passed in when pcall is called

The error message can be any value and is passed to the error function, which becomes the return value of pcall

  1. A complete exception handling process in Lua is usually:
    1. Use error to throw an exception
    2. Use pcall to catch exceptions
    3. Error messages are used to identify the type or content of the error

Error messages and traceability

  1. An error message is usually a string that describes what went wrong
  2. Lua encounters an internal error, such as indexing a non table value, and an error message will be generated
  3. In other cases, the error message is the value passed to the error function
  4. As long as the error message is a string, Lua appends some information about where the error occurred
  1. The second parameter of the error function, level, indicates which function in the call level should report the current error, that is, who is responsible for the error

When the pcall function returns an error message, it has destroyed part of the call stack

If you want to get a complete trace back to the function call when the error occurs, rather than just get the location where the error occurred, you need to use the xpcall function

The xpcall function takes two arguments

  1. Function to be called
  2. And an error handling function

When an error occurs, Lua will call the error handling function before the call stack is expanded, and you can use the debug library to get the wrong additional information.

Two general processing functions of debug library

  1. debug.debug, which provides a Lua prompt for the user to check the cause of the error
  2. debug.traceback, build an extended error message based on the call stack
  3. The interpreter uses debug.traceback to build its error messages
  4. Any time you call debug.traceback, you can get the currently executed call stack

Posted by mchip on Thu, 12 Mar 2020 21:54:50 -0700

Источник

Periodic «Lua: error in error handling» crashes #3011

The text was updated successfully, but these errors were encountered:

Try updating to the latest version.

Updating now. Any idea how I would know if its fixed? This happened at least half a dozen times and every time there seemed to be no common preceding log entry indicating an action that caused it.

seemed to be when running the code registered by minetest.register_on_craft

if it happens frequently then just run the server and see if it happens. If all good for a couple of days then please report your findings back here

Just happened again, or is this a new, unrelated thing?

@thatgraemeguy Yes, that is the same error. Yours happened inside of a minetest.register_entity on_step() callback.

Everybody, please list the mods you were using at the time you experienced the crash when reporting.

Taken from my world.mt:

If there’s any other info that will help let me know. I have all server’s console output logged. Implemented a cron to check if it ought to be running and isn’t, which has triggered 20+ times over the last 11 or so hours.

on OldCoders server:

My server has been running for nearly 24 hours without issue.

Same Problem here with the following Mods:

I think the Minetest Client should have a Feature to check if the Server is up.

Note: the scope of this bug is now to track «ocasionally my server throws this ‘error in error handling message’», if #3024 is resolved, and this bug still appears, we can find out whether its engine fault, or modder fault. If its modder fault, this bug can be closed.

Well, I guess it must be travelnet.

Try removing that mod and see if you get any errors.

@thatgraemeguy I am having trouble reproducing this error but you seem to have them quite regularly. What is the best way to get in touch with you?

I’m on IRC most of the time, Freenode and Inchra. Unfortunately I don’t seem to be getting it any more though.

I think this is a blocker issue because multiple people reported it, and had it very often.

maybe error handling doesn’t work in specific situations, e.g. digging and placing

@HybridDog thats what #3024 is about, this issue tracks error in error handling errors that are the engine’s fault.

Removed blocker status because frankly it’s too hard to track down and for some reason not many people seem to be having it any more. The frequency of the errors appears to periodically wax and wane. Probably due to some corrupted mod state being reset or the offending object removed.

@kwolekr has said it was likely the travelnet mod by sokomine, and not the engine, therefore closing this, as people also don’t report it anymore. It seems to be not the engine’s fault, that’s what matters.

Источник

Error in error handling lua

This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.

8.5 – Error Messages and Tracebacks

Although you can use a value of any type as an error message, usually error messages are strings describing what went wrong. When there is an internal error (such as an attempt to index a non-table value), Lua generates the error message; otherwise, the error message is the value passed to the error function. In any case, Lua tries to add some information about the location where the error happened: The location information gives the file name ( stdin , in the example) plus the line number (1, in the example).

The error function has an additional second parameter, which gives the level where it should report the error; with it, you can blame someone else for the error. For instance, suppose you write a function and its first task is to check whether it was called correctly: Then, someone calls your function with a wrong argument: Lua points its finger to your function—after all, it was foo that called error —and not to the real culprit, the caller. To correct that, you inform error that the error you are reporting occurred on level 2 in the calling hierarchy (level 1 is your own function):

Источник


Need for Error Handling

Error handling is quite critical since real-world operations often require the use of complex operations, which includes file operations, database transactions and web service calls.

In any programming, there is always a requirement for error handling. Errors can be of two types which includes,

  • Syntax errors
  • Run time errors

Syntax Errors

Syntax errors occur due to improper use of various program components like operators and expressions. A simple example for syntax error is shown below.

a == 2

As you know, there is a difference between the use of a single «equal to» and double «equal to». Using one instead of the other can lead to an error. One «equal to» refers to assignment while a double «equal to» refers to comparison. Similarly, we have expressions and functions having their predefined ways of implementation.

Another example for syntax error is shown below −

for a= 1,10
   print(a)
end

When we run the above program, we will get the following output −

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

Syntax errors are much easier to handle than run time errors since, the Lua interpreter locates the error more clearly than in case of runtime error. From the above error, we can know easily that adding a do statement before print statement is required as per the Lua structure.

Run Time Errors

In case of runtime errors, the program executes successfully, but it can result in runtime errors due to mistakes in input or mishandled functions. A simple example to show run time error is shown below.

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

add(10)

When we build the program, it will build successfully and run. Once it runs, shows a run time 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]: ?

This is a runtime error, which had occurred due to not passing two variables. The b parameter is expected and here it is nil and produces an error.

Assert and Error Functions

In order to handle errors, we often use two functions − assert and error. A simple example is shown below.

local function add(a,b)
   assert(type(a) == "number", "a is not a number")
   assert(type(b) == "number", "b is not a number")
   return a+b
end

add(10)

When we run the above program, we will get the following error output.

lua: test2.lua:3: b is not a number
stack traceback:
	[C]: in function 'assert'
	test2.lua:3: in function 'add'
	test2.lua:6: in main chunk
	[C]: ?

The error (message [, level]) terminates the last protected function called and returns message as the error message. This function error never returns. Usually, error adds some information about the error position at the beginning of the message. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.

pcall and xpcall

In Lua programming, in order to avoid throwing these errors and handling errors, we need to use the functions pcall or xpcall.

The pcall (f, arg1, …) function calls the requested function in protected mode. If some error occurs in function f, it does not throw an error. It just returns the status of error. A simple example using pcall is shown below.

function myfunction ()
   n = n/nil
end

if pcall(myfunction) then
   print("Success")
else
	print("Failure")
end

When we run the above program, we will get the following output.

Failure

The xpcall (f, err) function calls the requested function and also sets the error handler. Any error inside f is not propagated; instead, xpcall catches the error, calls the err function with the original error object, and returns a status code.

A simple example for xpcall is shown below.

function myfunction ()
   n = n/nil
end

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

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

When we run the above program, we will get the following output.

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

As a programmer, it is most important to ensure that you take care of proper error handling in the programs you write. Using error handling can ensure that unexpected conditions beyond the boundary conditions are handled without disturbing the user of the program.

Just happened again, or is this a new, unrelated thing?

2015-08-06 15:30:57: ACTION[ServerThread]: thatgraemeguy places node default:torch at (1607,3,1604)
2015-08-06 15:30:59: ACTION[ServerThread]: Blasus places node default:desert_sand at (1727,5,1566)
2015-08-06 15:31:00: ERROR[main]: UNRECOVERABLE error occurred. Stopping server. Please fix the following error:
2015-08-06 15:31:00: ERROR[main]: Lua: Double fault error in luaentity_Step(): error in error handling

In thread 7f19d8cab780:
/home/graeme/skyblock/src/server.cpp:511: void Server::step(float): A fatal error occurred: Lua: Double fault error in luaentity_Step(): error in error handling
Debug stacks:
DEBUG STACK FOR THREAD 7f19d08f7700:
#0  virtual void* EmergeThread::Thread()
(Leftover data: #1  MapBlock* ServerMap::loadBlock(v3s16))
(Leftover data: #2  void ServerMap::loadBlock(std::string*, v3s16, MapSector*, bool))
(Leftover data: #3  void ItemStack::deSerialize(std::istream&, IItemDefManager*))
DEBUG STACK FOR THREAD 7f19d10f8700:
#0  virtual void* CurlFetchThread::Thread()
DEBUG STACK FOR THREAD 7f19d18f9700:
#0  virtual void* ServerThread::Thread()
#1  void Server::Receive()
(Leftover data: #2  void Server::SendBlocks(float))
(Leftover data: #3  void RemoteClient::GetNextBlocks(ServerEnvironment*, EmergeManager*, float, std::vector<PrioritySortedBlockTransfer>&))
(Leftover data: #4  void ItemStack::serialize(std::ostream&) const)
(Leftover data: #5  bool getCraftingResult(Inventory*, ItemStack&, std::vector<ItemStack>&, bool, IGameDef*))
(Leftover data: #6  void ItemStack::deSerialize(std::istream&, IItemDefManager*))
(Leftover data: #7  void ItemStack::deSerialize(std::istream&, IItemDefManager*))
DEBUG STACK FOR THREAD 7f19d8cab780:
#0  int main(int, char**)
#1  Dedicated server branch
#2  void dedicated_server_loop(Server&, bool&)
#3  void Server::step(float)
(Leftover data: #4  void Server::SendAccessDenied_Legacy(irr::u16, const wstring&))

error handling

dynamic link

  1. In Lua, dynamic links are considered the parent of all other mechanisms

  2. So you can use it to dynamically load any other mechanism not in Lua

  3. Two parameters required for package.loadlib

    1. Full path to the library
    2. Correct function name
  4. The loadlib function loads the specified library and links it into Lua

  5. It does not call any functions in the library

  6. Instead, a function written in C is returned as a Lua function

  7. If an error occurs while loading the library or looking for the initialization function, nil and an error message are returned

local path = "c:/lua/5.1/socket.so"
local f = package.loadlib(path, "luaopen_socket")
  1. Usually use require to load the C library. This function will search the specified library
  2. Then load the library with loadlib and return the initialization function
  3. This initialization function should register the functions provided in the library with Lua, just like other functions defined in the Lua code block

error

  1. Lua is an extension language, usually embedded in applications

  2. If we crash or exit directly when an error occurs, we can’t capture where the error occurred

  3. So whenever Lua has an error, it should end the current block and return to the application

  4. Any unexpected condition in Lua causes an error, such as:

    1. Add two non numeric values
    2. Call on a value that is not a function
    3. Index a value that is not a Table
  5. You can explicitly raise an error by calling the error function

    1. Function that needs to pass in an error message
do
    print("enter a number:")
    n = io.read("*number")
    if not n then 
        error("invalid input")
    end
end
 
-- Equivalent to the above code
do
	print("enter a number:")
	n = assert(io.read("*number"), "invalid input")
end
  1. assert returns the first parameter if it is true
  2. If the first parameter is false or nil, an error will be raised
  3. The second parameter is an optional information string
  4. Its parameters are evaluated when assert is called
  5. In the following code, Lua will connect strings even if n is a numeric type
n = io.read()
assert(tonumber(n), "invalid input:" .. n .. " is not a number")
  1. When a function encounters an unexpected situation, i.e. «exception», two basic behaviors can be taken

    1. Return error code (usually nil)
    2. Raise an error (call error)
  2. sin passes in table as a parameter

-- Return an error code, check sin Function return value
local res = math.sin(x)
if not res then
	<Error handling code>
end

-- call sin Before, check the parameters
if not tonumber(x) then
   	<Error handling code> 
end
  1. Usually neither the parameters nor the return value of sin are checked

  2. You can stop the calculation and give an error message

  3. Non existence of io.open file or abnormal behavior when access is denied

  4. Whether a file exists or not can be verified by whether it can be opened

  5. When io.open is unable to open a file, nil should be returned with an error message attached

do
    local file, msg
    repeat
        print("enter a file name:")
        local name = io.read()
        if not name then
            return
        end
        -- io.open The first parameter is the file path, and the second parameter is the open mode, r Is character mode
        -- io.open If it succeeds, the file handle will be returned. If it cannot be opened, the file handle will be returned nil And error messages
        file, msg = io.open(name, "r")
        if not file then
            print(msg)
        end
	until file
end

-- Equivalent to the above code.On error message io.open The second return value of, and becomes the assert Second parameter of
do
    local file, msg
    repeat
        print("enter a file name:")
        local name = io.read()
        if not name then
            return
        end
       file = assert(io.open(name, "r"))
	until file
end

Error handling and exceptions

  1. In most cases, you don’t need to do any error handling in Lua, which is the responsibility of the application calling Lua

  2. Because all Lua activities start with a single call from the application

    1. Lua is usually required to execute a block
    2. If an error occurs, the call returns the error code and is processed by the application
  3. When an error occurs in the interpreter program, the main loop prints the error message, then continues to display the prompt and waits for subsequent commands to be executed

  4. When handling errors in Lua, pcall must be used to wrap the code to be executed. P > means protect

  5. pcall can catch any errors raised when a function executes

    1. If there are no errors, it will return true and the return value of the function call
    2. If there is an error, it will return false and error message
-- Execute a paragraph Lua Code,To capture all errors in execution, you need to encapsulate this code into a function
function foo()
    <code block>
    if Unexpected conditions then 
        error()
    end
    <code block>
    print(a[i]) -- Potential errors, a Maybe not one table
    <code block>
end

if pcall(foo) then
    -- implement foo No error occurred at
    <Regular code>
else
    -- foo An error was raised for error handling
    <Error handling code>
end
  1. An anonymous function can be passed in when pcall is called

  2. The error message can be any value and is passed to the error function, which becomes the return value of pcall

if pcall (function ()
	-- <Protected code>        
    return 20 + 10 -- Code for testing "a" + 10
end) then
    -- <Regular code>
    print("ok")
else
    -- <Error handling code>
    print("error")
end

do
	local status, err = pcall(function ()
        error({code = 121})
 	end)
    print(status, err.code)
end
  1. A complete exception handling process in Lua is usually:
    1. Use error to throw an exception
    2. Use pcall to catch exceptions
    3. Error messages are used to identify the type or content of the error

Error messages and traceability

  1. An error message is usually a string that describes what went wrong
  2. Lua encounters an internal error, such as indexing a non table value, and an error message will be generated
  3. In other cases, the error message is the value passed to the error function
  4. As long as the error message is a string, Lua appends some information about where the error occurred
do
    local status, err = pcall(function () a ="a"+1 end)
    print(err)
end

do
    local status, err = pcall(function () 
            error("my 	error") 
    end)
    print(err)
end
-- Location information contains file name stdin And line number 3
-- stdin:3: my error
  1. The second parameter of the error function, level, indicates which function in the call level should report the current error, that is, who is responsible for the error
-- In a function, check at the beginning whether the passed in parameter is correct
do
    function foo(str)
        if type(str) ~= "string" then
            -- If the second parameter is not added, it is considered to be an error in reading the function and an error is reported, stdin:3: string expected
            -- error("string expected")
            -- With the second parameter, an error is considered at the call level and reported, stdin:9: string expected
            error("string expected", 2)
        end
        print(str)
    end

    foo({x = 1})
end

  1. When the pcall function returns an error message, it has destroyed part of the call stack

  2. If you want to get a complete trace back to the function call when the error occurs, rather than just get the location where the error occurred, you need to use the xpcall function

  3. The xpcall function takes two arguments

    1. Function to be called
    2. And an error handling function
  4. When an error occurs, Lua will call the error handling function before the call stack is expanded, and you can use the debug library to get the wrong additional information.

Two general processing functions of debug library

  1. debug.debug, which provides a Lua prompt for the user to check the cause of the error
  2. debug.traceback, build an extended error message based on the call stack
  3. The interpreter uses debug.traceback to build its error messages
  4. Any time you call debug.traceback, you can get the currently executed call stack
do
    local t = {2, 4, 6, 8 ,10}
    for i,v in ipairs(t) do
       	print(i, v)
        print(debug.traceback())
    end
end

This article is published by one article multiple platform ArtiPub Automatic publishing

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
   print(a)
end

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
do
   print(a)
end

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
end

add(10)

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
end
add(10)

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

Syntax:

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

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
end

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

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)
false

Понравилась статья? Поделить с друзьями:
  • Error in element formulation
  • Error in dna replication
  • Error in dmapi
  • Error in dir exists x file name conversion problem name too long
  • Error in dimnames x dn length of dimnames 2 not equal to array extent