Book Excerpt-12

Source: Internet
Author: User
Tags assert error code error handling lua

Data excerpt from <lua Programming (second Edition) >

compile, execute
Dofile is a built-in operation for running LUA code blocks. But in fact Dofile is an auxiliary function, LoadFile does the real core work. LoadFile loads a LUA block of code from a file, but it does not run the code, just compiles the code and then returns the compiled result as a function. General Dofile can be defined like this:
function dofile (filename)
Local F = assert (LoadFile (filename))--note that if LoadFile fails, assert throws an error
return F ()
End
Create a file Test.lua with the following content:
Local i = 1
For n=1,10 do
i = i + 1
End
Print (i)
Then perform the dofile operation:
Dofile ("Src/test.lua")-->11 here must pay attention to the path
The function loadstring is similar to loadfile, except that it reads code from a string, rather than reading from a file, such as:
f = LoadString ("i = i + 1")
F becomes a function that executes i = i + 1 each time it is called
Here's a place to be aware of:
i = 32
Local i = 0
f = LoadString ("i = i + 1;print (i)")
g = function () i = i + 1;print (i) End
F ()-->33
G ()-->1
As shown above, function G operates the local I as expected, but F operates on the global I, because loadstring always compiles its string in the global environment.
Further research on LoadFile and LoadString will reveal that there is actually a real primitive function load in Lua. LoadFile and LoadString read the block separately from the file and the string, and load receives a "reader function" and calls it internally to get the block.

Package.loadlib
All of the functionality that LUA provides for dynamic linking is clustered in a function, the package.loadlib. The function has two string arguments: The full path of the dynamic library and a function name.
Local Path = "/usr/local/lib/lua/5.1/socket.so"
Local F = package.loadlib (path, "Luaopen_socket")
F ()
Loadlib loads the specified library and links it to Lua. However, it does not call any functions in the library. Instead, it returns a C function as a LUA function.
Loadlib is a very low-level function that must provide the full path to the library and the correct function name. The C library is typically loaded with require, which searches for the specified library, then loads the library with Loadlib and returns the initialization function.

Error
Because Lua is an extended language, it is usually embedded in the application, so it cannot simply crash or exit when an error occurs. Instead, as soon as an error occurs, LUA should end the current block and return to the application.
Any unexpected conditions that Lua encounters will raise an error. You cannot explicitly throw an error by calling the error function and passing in an argument to the wrong message. Usually this function is a more appropriate way to handle the error:
Print "Enter a number"
n = io.read ("*number")
If not n then error ("Invalid input") end
Because a combination such as "if Not<condition> then Error end" is very common code, LUA provides a built-in function assert to accomplish this kind of work:
Print ("Enter a number")
n = assert (Io.read ("*number"), "Invalid input")
When a function encounters an unexpected condition ("exception"), it can take two basic behaviors: return an error code (usually nil) or throw an error (calling error). There is no fixed rule between the two, but the usual guideline is that an exception that is easy to avoid should cause an error, otherwise the error code should be returned.
If you need to handle errors in Lua, you must use Pcall to wrap the code that needs to be executed.
Assuming that all errors thrown during execution are captured while executing a piece of LUA code, the first step is to encapsulate the code in a function, such as
function foo ()
< some code >
If unexpected condition then error () end
< some code >
Print (A[i])--Potential error: A may not be a table
< some code >
End
Then use Pcall to invoke Foo:
If Pcall (foo) then
--no error occurred while executing foo
< general code >
Else
--foo caused a mistake to take appropriate action
< error handling code >
End
The Pcall function invokes its first argument in a "protected mode", so pcall can catch any errors in the execution of the function. If no error occurs, Pcall returns True and the return value of the function call; otherwise, false and error messages are returned.
Note that the "error message" can be any type of LUA value, not just a string, such as:
Local Status,err = Pcall (function () error ({code=121}) end)
Print (Err.code)-121
Although you can use any type of value as an error message, the error message is usually a string that describes the content of the error. When an internal error is encountered, LUA generates an error message. At other times, the error message is the value passed to the error function. As long as the error message is a string, Lua appends some information about where the error occurred:
Local Status,err = Pcall (function () a = "a" + 1 end)
Print (ERR)-->e:\cocos2dprojects\mytest100\src\main.lua:64:attempt to perform arithmetic on a string value

Local Status,err = Pcall (function () error ("My error") end)
Print (ERR)-->e:\cocos2dprojects\mytest100\src\main.lua:64:my error
Typically, when an error occurs, you want to get more debugging information, rather than just where the error occurred. At the very least, it can be traced back to the function call when the error occurred, showing a complete function call stack. When Pcall returns its error message, it has destroyed part of the call stack. Therefore, if you want to get a meaningful call stack, you must obtain that information before Pcall returns. To meet this requirement, LUA provides a function xpcall. In addition to accepting a function that needs to be called, the function accepts the second parameter-an error handler. When an error occurs, LUA invokes the error handler before the call stack is expanded. You can then use the debug library in this function to get additional information about the error. The Debug library provides two common error-handling functions: One is Debug.debug, which provides a LUA prompt for the user to examine the cause of the error, and the other is Debug.traceback, which builds an extended error message based on the call stack.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.