Lua Tutorial (vi): Compile execution and error _lua

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

1. Compile:
The Dofile function is provided in Lua, which is a built-in operation for running LUA blocks of code. But actually Dofile is just an auxiliary function, LoadFile is the real core function. Instead of Dofile,loadfile just loading the LUA code block from the specified file, and then compiling the block of code, if there is a compilation error, the nil is returned and the error message is given, but the code block is not really executed after the compilation succeeds. Therefore, we can implement the Dofile as:

Copy Code code as follows:

function dofile (filename)
Local F = assert (LoadFile (filename))
return F ()
End

Here if LoadFile execution fails, the Assert function raises an error directly. With the Dofile code, we can also see that if you plan to run the LUA code block in a file multiple times, we can only execute loadfile once, then run it back multiple times, so we can save the overhead of multiple compilations. This is also the difference between the performance of LoadFile and Dofile.
LUA also provides another way to dynamically execute the LUA code, the LoadString function. As the name suggests, the code source for loadfile,loadstring is from a string in its argument, such as:
f = LoadString ("i = i + 1")
At this point, F becomes a function that executes "i = i + 1" each time it is invoked, such as:
Copy Code code as follows:

i = 0
F ()
Print (i)--will output 1
F ()
Print (i)--will output 2

LoadString is really a powerful function, but the resulting performance overhead is something we have to consider. So for many constant strings, if you still use the LoadString method, that doesn't make much sense, as the example above F = loadstring ("i = i + 1"), because we can completely replace it with the form f = function () i = i + 1 end. And the latter is far more efficient than the former. After all, the latter is compiled only once, while the former is compiled every time loadstring is invoked. For LoadString, we also need to note that the function always compiles its string in the global environment, so it will not be able to file local variables, but can only access global variables, such as:
Copy Code code as follows:

i = 32
Local i = 0
f = LoadString ("i = i + 1"; Print (i) ")
g = function () i = i + 1; Print (i) end
The I in the F ()--f function is the global variable I, so output 33
G () The I in the--G function is the local variable i, so output 1

For functions returned by loadstring, if you need to evaluate an expression, you must add a return before it so that you can form a statement that returns the value of the expression, such as:
Copy Code code as follows:

i = 32
f = LoadString ("i = i + 1"; return I * 2 ")
Print (f ())--Output 66
Print (f ())--output 68. Because loadstring returns a normal function, it can be called repeatedly.

LUA treats all stand-alone blocks as functions of an anonymous function, and the anonymous function also has variable-length arguments, so you can pass arguments to LoadString when you invoke it, such as:
Copy Code code as follows:

Local i = 30
--The following ... Represents a variable-length argument that assigns a value to a local variable x.
Local F = assert (LoadString) ("local x = ...; Return (x + 10) * 2 "))
For i = 1, does
Print (String.rep ("*", f (i))
End

2. C Code:

The previous section describes the dynamic loading of the LUA code, and in fact, LUA itself supports the dynamic loading of code in the C dynamic library, and to do so, we need to take advantage of the LUA built-in system function Package.loadlib. The function has two string parameters, which are the full file name of the dynamic library and the name of the function that the library contains, and the typical calling code is as follows:

Copy Code code as follows:

Local Path = "/usr/local/lib/test.so"
Local F = package.loadlib (path, "Test_func")

Because Loadlib is a very low-level function, the full pathname and function name must be supplied at the time of invocation.

3. Error:
Lua, as an embedded scripting language, should not simply exit or crash in the event of an error. In contrast, if an error occurs, LUA should end the current block and return to the application.
In Lua we can get error messages through the error () function, such as:

Copy Code code as follows:

Print "Enter a number:"
n = io.read ("*number")
If not n then error (' Invalid input ') end

The last line in the previous code we can use the additional built-in function assert class support through LUA, for example:
Copy Code code as follows:

Print "Enter a number:"
n = assert (Io.read ("*number"), "Invalid input")

The Assert function checks whether the first argument is true, and if so, simply returns the argument, or an error is raised. The second parameter is an optional string.
Error handling is a very important part of all programming languages. In the actual development, there is no uniform guiding principle, only in the face of problems, after careful analysis in combination with the application of the scene at the time, and finally combined with their own experience to give the wrong concrete treatment. In some cases, we can return the error code directly, and in other cases, we need to throw the error directly, allowing the developer to quickly locate the source of the code that caused the error.

4. Error handling and Exceptions:

LUA provides the error-handling function Pcall, the first parameter of which is a function that requires "protect execution," and if the function fails, Pcall returns false and an error message, or returns True and the return value of the function call. See the following code:

Copy Code code as follows:

function foo ()
Local A = 10
Print (a[2])
End

R, msg = Pcall (foo)
If R then
Print ("This is OK.")
Else
Print ("This is error.")
Print (msg)
End
--The output result is:
--this is error.
--d:/test.lua:3: Attempt to index local ' a ' (a number value)

We can also pass anonymous functions directly to the Pcall function, such as:

Copy Code code as follows:

R, msg = Pcall (function () error ({code = 121}) end)
If R then
Print ("This is OK.")
Else
Print ("This is error.")
Print (Msg.code)
End
--The output result is:
--this is error.
--121

5. Error message and Retrospective:

Often, when an error occurs, you want more debugging information, not just where the error occurred. At least as far back as the error occurred and function call case, display a complete function call stack trajectory. To do this, we need to use another built-in function Xpcall provided by LUA. In addition to accepting a function that needs to be called, the function accepts the second argument, the error-handling function. When an error occurs, LUA calls the error-handling function before the call stack is expanded. In this way, we can use the Debug.traceback function of the debug library in this function, which constructs an extended error message based on the call stack. Such as:

Copy Code code as follows:

function Errorfunc ()
Local A = 20
Print (a[10])
End

function Errorhandle ()
Print (Debug.traceback ())
End

If Xpcall (Errorfunc,errorhandle) Then
Print ("This is OK.")
Else
Print ("This is error.")
End

--The output result is:
--[[stack Traceback:
D:/test.lua:7: in function <d:/test.lua:6>
D:/test.lua:3: in function <d:/test.lua:1>
[C]: in function ' Xpcall '
D:/test.lua:10:in main Chunk
[C]:?
This is error.
--]]

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.