Lua compiler and run

Compile-Run

Although we as interpreted language Lua, Lua but the code will first pre-compiled into intermediate code and then execute (many interpreted languages ​​are doing so). Compilation phase in the presence of an interpreted language sounds inappropriate, however, it features an interpreted language is not whether they have been compiled, but the compiler is part of the language runtime, so the compiler generates intermediate code execution speed will be faster . We can say that there is a description of the function dofile Lua can be invoked as an interpreted language.

Earlier we introduced dofile, put it as a chunk of Lua code is running the original operation. dofile is actually a secondary function. Function is true completion loadfile; is different from the dofile loadfile compiled code into intermediate code and returns the compiled chunk as a function, without executing the code; loadfile addition does not throw an error message instead returns an error generations. We can define dofile:

function dofile (filename) 
local f = assert(loadfile(filename)) 
return f() 
end 

If loadfile failed assert will throw an error.

Complete a simple function dofile more convenient, he reads the file is compiled and executed. However loadfile more flexible. In the event of an error, loadfile returns nil and an error message, so that we can customize the error handling. In addition, if we run a file multiple times, then, loadfile need only to compile once, but can be run multiple times. dofile
but every time compilation.

loadstring and loadfile similar, but it is not a chunk read from a file, but read from a string.
E.g:

f = loadstring("i = i + 1") 
f 将是一个函数,调用时执行 i=i+1
i = 0 
f(); print(i) --> 1 
f(); print(i) --> 2 

loadstring function is powerful, but need to be careful when using. Verify that no other simple way to solve the problem of re-use.

Lua to each chunk are treated as an anonymous function. For example: chunk "a = 1", loadstring return to its equivalent function () a = 1 end and the other function, chunks can define local variables can also return values:

f = loadstring("local a = 10; return a + 20") 
Programming in Lua 48
Copyright ® 2005, Translation Team, www.luachina.net 
print(f()) --> 30 

loadfile and loadstring will not throw an error if an error occurs they will return nil plus the error message:

print(loadstring("i i"))  --> nil [string "i i"]:1: '=' expected near 'i' 

In addition, loadfile and loadstring boundary effects will not be produced, they just compiled chunk as a function of its own internal implementation of anonymous. They usually misunderstanding is that they define a function. Lua function definition is the assignment occurs at runtime rather than at compile time. If we have a file foo.lua:

-- file `foo.lua' 
function foo (x) 
 print(x) 
end 
当我们执行命令 f = loadfile("foo.lua")后,foo 被编译了但还没有被定义,如果要定义他必须运行 chunk:
f() -- defines `foo' 
foo("ok") --> ok 

If you want to call dostring efficient (such as load and run), it can be

loadstring(s)() 

The results loadstring call returned, however, if the loaded content if there is a syntax error, loadstring returns nil and an error message (attempt to call a nil value); in order to return a clearer Error messages can assert:

assert(loadstring(s))() 

Loadstring usually does not make sense to load a string, for example:

f = loadstring("i = i + 1") 

Probably with f = function () i = i + 1 end equivalent, but the second paragraph of the code is faster because it only needs to be compiled once, each call loadstring first piece of code will be recompiled, there is an important difference: loadstring compile time do not care lexical scope:

local i = 0 
f = loadstring("i = i + 1") 
g = function () i = i + 1 end

In this example, and imagine using the same local variables g i, however, the use of global variables f i; loadstring always compiled his string in the global environment.
loadstring commonly used external running program code, such as running user-defined code. Note:
the loadString expect a chunk, namely statements. If you want to load expression, and needs return, as the return value of the expression prior to expression. Look at an example:

print "enter your expression:"
local l = io.read() 
local func = assert(loadstring("return " .. l)) 
print("the value of your expression is " .. func()) 
loadstring 返回的函数和普通函数一样,可以多次被调用:
print "enter function to be plotted (with variable `x'):"
local l = io.read() 
local f = assert(loadstring("return " .. l)) 
for i=1,20 do
 x = i -- global `x' (to be visible from the chunk) 
 print(string.rep("*", f())) 
end 

require function

Lua provides advanced require function to load the runtime. Roughly speaking require and dofile perform the same function but with two exceptions:

  1. require load file directory searches
  2. require will determine whether a file has been loaded to avoid duplication of the same file to load. Due to the above characteristics, require a better function to load the library in Lua.

Path require the use of common and we see some differences path, we generally see the path is a directory listing. Require that a path pattern list, a pattern indicating a process for each of the virtual file name (parameter require) is converted to a real file names. More specifically, each model is an optional question mark contains the file name. When matched Lua will first replace the question mark with the virtual file name, and then see if there is such a file exists. If there is no match with the second pattern continues in the same manner. For example, the following paths:

?;?.lua;c:\windows\?;/usr/local/lua/?/?.lua 
调用 require "lili"时会试着打开这些文件:
lili 
lili.lua 
c:\windows\lili 
/usr/local/lua/lili/lili.lua 

Issues require attention only a semicolon (the separator between modes) and question marks, other information (directory separator character file extension) is defined in the path. In order to determine the path, Lua global variables LUA_PATH first check whether a string is considered if the string is the path; otherwise LUA_PATH require checking the value of the environment variable, if both fail require the use of a fixed path (the typical "?; ? .lua ")

Another is to avoid duplication of functions require load the same file twice. Lua Keep a list of all the files have been loaded (using the table to save). If you load a file exists in the table require a simple return; vanity table reserved loaded files, not the actual file name. So if you use different virtual file names require twice the same file, the file will be loaded twice. For example, require "foo" and require "foo.lua", path ";??. Lua" will load foo.lua twice. We can also access global variables _LOADED list of file names, so that we can determine whether the file is loaded too; Similarly, we can use a little trick to make require loading a file twice. For example, after require "foo" _LOADED [ "foo"] will not nil, we can assign it to nil, require "foo.lua" will load the file again.

A path pattern may contain not only a question mark and a fixed path, such as:

?;?.lua;/usr/local/default.lua 

In this case, when there is no match will require the use of the fixed file (of course, this path must be fixed on the last meaningful pattern list). In operation require a chunk ago, it defines a global variable _REQUIREDNAME filename used to save the virtual file is required. We may require extended functionality through the use of this technique. To give an extreme example, we can set the path to
"/usr/local/lua/newrequire.lua", so that later require newrequire.lua runs every call, in which case you can go through the actual value of the use of _REQUIREDNAME load the required files.

C Packages

Lua and C is easily combined with C to write Lua package. Package and write in different Lua, C package must first be loaded before use and connection is through a dynamic link library mechanism in most systems the easiest to achieve, but the dynamic link library is not part of the ANSI C, that is the standard C in dynamic connection is very difficult.

Lua generally does not contain any mechanism can not be implemented in standard C, it is a special case of the dynamic link library. We can be seen as dynamic link library mechanism other mechanisms of the mother: Once we have the dynamic connection mechanism, we can dynamically load Lua mechanism does not exist. So, in this particular case, Lua broke his platform compatible principles to realize the connectivity platform for a number of mechanisms by way of conditional compilation. Standard Lua as windows, Linux, FreeBSD, Solaris and other Unix platforms implements this mechanism, expand to other platforms support this mechanism is not difficult. Looking at the results returned by running in Lua prompt print (loadlib ()), if the display is bad arguments explain your release supports dynamic connection mechanism, or explain the dynamic connection mechanism does not support or is not installed.

Lua provides all the functionality of dynamic linking in a function called loadlib of. This function takes two parameters: the absolute path to the library and initialization function. So an example of a typical call is as follows:

local path = "/usr/local/lua/lib/libluasocket.so"
local f = loadlib(path, "luaopen_socket") 

loadlib function loads the specified library and connected to Lua, but it does not open the library (that is to say not call the initialization function), otherwise he returns initialization function as a Lua function, so that we can call him directly in Lua. If the error occurred while loading a dynamic library or check initialization function, loadlib returns nil and an error message.

We can modify the previous piece of code, it detects the error and then calls the initialization function:

local path = "/usr/local/lua/lib/libluasocket.so"
-- or path = "C:\\windows\\luasocket.dll" 
local f = assert(loadlib(path, "luaopen_socket")) 
f() -- actually open the library 

Under normal circumstances we expect the release of the binary libraries contain similar stub file a previous code snippet, the installation binaries can be easily placed in a directory, you only need to modify the actual path to the stub file corresponding to binary library. The directory where the file will be added to the stub LUA_PATH, this setting can be used after loading the C library functions require up.

Published 252 original articles · won praise 151 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_39885372/article/details/104334251