Lua Drain 0

lua compiler download address: https://github.com/rjpcomputing/luaforwindows/releases
Version: LuaForWindows_v5.1.5-52
Books: Lua-Chinese
1. In the conditions of the control structure, except for false and nil, all others are true, that is, 0 and empty strings are also true.

2. Common escape sequences: \n (line feed), \t (tab character), \r (carriage return)

3. Available [[..]] Represents a string. The string of this representation supports multiple lines, can be nested and does not explain the escape statement. If the first line is a newline character, it will be automatically ignored. If [[..]] is nested in [[..]], it needs to be written in the form of [=[..[[..]]..]=], where = can be any number, but before and after it is required The number is the same.
Example:

page = [==[ <"this is a test"\> [[<"this is a body test"\>]] ]==]print(page);

4. When used.. connect two numbers In order to avoid interpretation errors, you need to add a space after the number

print (10 .. 20) span>

5. If the parameter in tonumber is not a string, the return value is nil

6.==When comparing tables, userdata, functions, compare their references, the references are inconsistent, Even if the content is the same, it is false

7.a and b: If a is false, return a, otherwise return b. a or b: If a is true, return a, otherwise return b. The result of not always returns true or false.
This rule can be used to assign an initial value when x is false or nil: x = x or v

8. Implementation of ternary operator: a? b: c ⇒ (a and b) or c

9. The table can be initialized directly by assignment, or it can be initialized by any expression. When initializing a table as a record: a = {x = 0, y = 0} => ax = 0; ay = 0; =>a[“x”] = 0, a[“y”]=0 => {[“X”] = 0,[“y”] = 0}, where the separator can be used or ;, usually we use; to separate different types of table elements.
Example: Linked list implementation

local list = nil;for< /span> k,line in pairs({"begin","yes","no","end"}) do list = {next = list, value = line}endwhile list do print("this is list value "..< span class="hljs-built_in">list.value); list = list.next;end

10.lua can assign values ​​to multiple variables at the same time. Variables The elements of the list and the value list are separated by. The value on the right side of the assignment statement will be assigned to the value on the left in turn. And Lua will first calculate all the values ​​on the right, and then perform the assignment operation. According to this feature, variable exchange can be realized like this
Example:

a = 1;b = 2;a,b = b,a;print("this a and b ". . a ..":"..b)

11. When assigning , If the number of variables is inconsistent with the number of values, if the number of variables is more than the number of values, the excess variables are assigned nil, if the number of variables is less than the number of values, the excess values ​​will be ignored.

12. An example of scope:

x = 10local i = 1while i <= x do --External x local x = i * 2; --internal x print(x) ; i = i + 1;endif i> 20 then local x; x = 20; print(x + 2);else print(x);endprint(x);

13. Two benefits of using local variables (local): avoid naming conflicts, and access speed of local variables Faster than global variables.

14.do..end sentence pattern can delimit a more definite block for the block, the scope of the local variable in this is included between do..end.
15. Control statement sentence pattern: if…then…end,if…then…else…end,if…then…elseif…then…else….end

16.while statement: while… do…end

17. repeat-until statement: repeat…until…

18. for statement: for beginvalue, endvalue, stepvalue do…end => where beginvalue, endvalue, stepvalue All are local variables
for k, v in ipairs(a) do… end, for k, v in pairs(a) do… end => where k, v are local variables

19. Lua syntax requires that break and return can only appear at the end of the block, that is, before end or else or until, you can also use do break/return end to achieve this.

20. When the function is called, if the function parameter is a string or a table structure, it is not necessary to write ()
Example:

function f(table)  print "this is a table func";endprint "Hello World";f{"table"}

21. The matching of function parameters and actual parameters is similar to assignment statements, the redundant part is ignored, and some nil is missing.

22. For multi-return value functions, () can be used to force a return value.
Example:

function f2() return "a","b";end--Output: abprint(f2());--Output: a(f2()); span>print((f2()));--Output: acprint(f2(),"c");--Output: adprint(f2().."d");local tableA = {"1",f2()};for k, v in pairs(tableA) do --Output: 1:1,2:a,3:b print("this is tableA key and value: "..k..":"< /span>..v);endlocal tableB = {"1",f2(),"3"};for k,v in pairs(tableB) do --Output: 1:1,2:a,3:3 print("this is tableB key and value: "..k..":"..v);endtemp1,temp2,temp3 = f2();--Output:ab nilprint< /span>(temp1,temp2,temp3);b1,b2,b3 = f2(),10 ,30;--Output: a,10,30 print(b1,b2,b3);function f0< /span>()enda1,a2 = f0(),10,30;--Output: nil,10< span class="hljs-built_in">print(a1,a2);

23.unpack returns all the parameters of table
Example:

function f(a,b,c) print(a,b,c); endlocal a = {"a","b","c"};f(unpack(a));

The unpack is implemented in C language, and the implementation in Lua can be expressed as follows:
Example:

function unpack(t ,i) local i = i or 1; if t[i] then return t[i],unpack(t,i+1); endend

24.lua function can use… to accept a variable number of parameter. At this time, Lua said that the function parameters are placed in a table of arg. This table also contains a field n representing the number of parameters. The value of a variable number of parameters can be obtained by traversing the variable arg.

25 You can use dummy variables _ to skip some function return values

26.table sorting
Example:

network = {{name = "grauna",IP = "210.26.30.34"}, {name = "arraial",IP = "210.26.30.23"}, {name = "lua",IP = "210,26,30,12"}, {name = "derain" ,IP = "210.26.23.20"},}table.sort(network,function(a,b) return (a.name end);for k ,v in pairs(network) do print("this is network: "..k. .":"..v.name..":"..v.IP);< span class="hljs-keyword">end

27. The function in Lua is the first type of value with lexical demarcation. The first type of value refers to: in Lua, functions are the same as other values ​​(numerical values, strings). Functions can be stored in variables or tables, used as function parameters, and can also be used as function return values. Lexical delimitation means: the nested function can access the variables in his outer function (the realization of the closure, and then the closure can be used to implement the iterator).

28. Closure
Example

function

span> newCounter()
local span> i = 0; --returns an anonymous function, at this time the variable i is stored in upvalue < span class="hljs-keyword">return
function( ) --i is called an external local variable or upvalue i = i + 1< /span>; return i; endendc1 = newCounter();--output 1print(c1());--Output 2print(c1());c2 = newCounter();--Output 1 print(c2());

29. If the local function is a recursive function, it is best to write a pre-function declaration, otherwise due to Lua I don’t know if the function is a local function. Lua goes back to find out if there is such a global function.
Example:

local f = function (n) if n == 0 then return 1; else return n * f(n-1); endend

Because Lua encounters fact(n-1) when compiling and does not know that it is a local function fact. Lua goes back to find whether there is such a global function fact. In order to solve this problem, we must declare it before defining the function.

local f;f = function (n) if n == 0 then return  1; else return n * f(n-1); endend

It can also be expressed as

local f;function  f (n)  if n == 0 then retu rn 1; else return n * f(n-1); endend print(f(10));

30.lua In the return g(…) format, the call is called tail call (remember that it must be in this format, return g(…)+1 is not a tail call)
Example:

function g()endfunction f() return g();end

In the example, f does not do anything after calling g. In this case, when The program does not need to return to the caller f when the called function g ends; therefore, the program does not need to keep any information about the caller in the stack after the tail call. Some compilers, such as the Lua interpreter, use this feature to process tail calls without using additional stacks. We say that this language supports correct tail calls. Since tail calls do not need to use stack space, the level of tail call recursion can be unlimited. For example, the following call will not cause stack overflow regardless of the value of n.
Example:

function f(n) if n> 0 then return f(n-1); endend

31. Iterators and normative for statements

function list_iter(t) local i = 0; local n = table.getn(t) ; return function( ) i = i + 1; if i <= n then return t[i] end; endendt = {10,20,30}local iter = list_iter(t) ;while true do local element = iter(); if element == nil then break; end print(element);endfor element in list_iter(t) do print span>(element);end

or

function allwords() local state = {line = io.read(),pos = 1}; return allwords_itera,state;endfunction allwords_itera(state) while state.line do local< /span> s,e = string.find(state.line, "%w+",state.pos); if s  then state.pos = e + 1; return string.sub(state.line,s,e); else state.line = io< /span>.read(); state.pos = 1; end end return nil;end for word in allwords() do< /span> print("this is word :"..word);end

32.dofile,loadfile,dostring,lo Adstring implementation, remember that loadstring always compiles his string in the global environment.

function dofile span>(filename) local f =  assert(loadfile(filename)); return f();endloadstring([[print("this is loadstring")]])();
i = 0;--i only Can be a global variablef = loadstring("i = i + 1");f ();print(i);f()print(i);--output nil and error informationprint(loadstring( "ii"));

33.dofile and require are roughly the same in function, but their difference is: require will search the directory to load files, and require will determine whether the directory has been loaded. Avoid loading the same file repeatedly. Due to the above characteristics, require is a better function for loading libraries in Lua.
The path of require is a list of patterns. Each pattern specifies a way to convert the name of a virtual function (the way of require) to a real file name. To be more precise, each pattern contains an optional The file name of the question mark. When matching, Lua will first replace the question mark with the virtual function name to see if there is such a file. If it does not exist, continue to use the same method to match the second pattern.
Example:

When the path is as follows:?;?.lua;c:\windows\?;/user/local/lua/?/?.lua will try to open these files when calling require "lili" lililili.luac:\windows\lili/usr/local/lua/lili/lili.lua

That is, Lua only cares about semicolons ;, that is, the separator between patterns, and the question mark, other information (directory separator, file extension) is defined in the path.
To determine the path, Lua first checks whether the global variable LUA_PATH is a string, and if it is, it defaults to a path. Otherwise, require checks the value of the environment variable LUA_PATH, if both fail, require uses a fixed path (typical?;?.lua)
Another function of require is to avoid loading the same file twice. Lua will save a list of loaded file paths (save with table). If a loaded file exists in the table, require simply returns. The fictitious name of the loaded file is kept in the table instead of the real file name. So if you require the same file twice with different virtual file names, the file will be loaded twice.
Example:

require foorequire foo. lua path :?;?.lua will load the foo file 2 times

We can also use the global variable _LOADED to access the file name list. In this way, we can determine whether a file has been loaded. Similarly, we can also use a little trick to make require load a file twice.
Example:

After

require "foo" The value of _LOADED["foo"] will not be nil, we can add _LOADED[ The value of "foo"] is set to nil, thereby require  "foo" will load the file again

A path pattern can also not contain a question mark, but just a fixed path
Example

?;?.lua;/usr/local/default .lua In this case, when there is no match in require, this fixed path will be used (of course, the fixed path must be placed in the last digit to make sense ). 

Before requiring to run a chunk, he defined a global variable _REQUIRENAME to save the required virtual file name.
Example:

 We can set the path to "/usr/local/lua/newrequire.lua", In this way, newrequire.lua will be run every time you call require. In this case, you can actually load the required file by using the value of _REQUIREDNAME. 

(Note that the output of the above _LOADED, _REQUIREDNAME is nil in version 5.1 lua, and the variable may have been discarded, you can use package.loaded instead)

34.lua supports dynamic The link library loading c function can use package.loadlib() to check whether the current version supports the dynamic link mechanism.
Example:

local

span> path = "/usr/local/lua/lib/libluasocket.so";--package.loadlib parameter Is the absolute path and initialization function of the libraryprint(package.loadlib(path,"luaopen_socket"));local f = package .loadlib(path,"luaopen_socket"); Output: nil The specified module cannot be found. Open shows that the current version supports the dynamic link mechanism, but the specified module was not found. package.loadlib loads the developed library and links to lua, but does not open the library (that is, does not call the initialization function), otherwise it returns the initialization function as a function of lua , So we can call them directly in lua. If there is an error in loading the dynamic library or finding the initialization function, then package.loadlib will return nil and an error message.

35. Two ways to throw error messages: error, assert
Example:

print< /span> "enter a number:"n = io.read("*number");if not n then error("invalid input")end
print "enter a number :"assert(io.read( "*number"),"invalid input");assert will check first Whether each parameter returns an error, if there is no error, then assert simply returns, otherwise assert will be the second One parameter throws an error message, and the second parameter is optional. 

36. Catch exceptions: pcall calls his first parameter and runs in protected mode, so it can catch all exceptions and errors. If there is no error, pcall returns true and any value returned by the call, otherwise it returns nil and an error message. The error message does not have to be a string, the information passed to error will be returned by pcall. When pcall returns the error message, it has released the stack information that saves the error occurrence, so if we want to get tracebacks, it must be in pcall Get before returning. Lua provides xpcall to achieve this function, xpcall accepts two parameters: calling function and error handling function.
Example

local status,err = pcall (function () error({code = 112}) end);< span class="hljs-built_in">print(status,err.code); output: false 112 

37. Call debug.traceback to get the current traceback information.

38.Lua stores the environment variable itself in a global variable _G, and _G._G = _G

for n in pairs(_G) do print(n);end output: collectgarbagegetmetatable(.. .The remaining output is omitted)
function getfield(f) local v = _G; for w in string.gfind(f,"[%w_]+")  do v = v[w]; end return v;endfunction setfield< span clas s="hljs-params">(f,v) local t = _G< /span>; for w,d in string span>.gfind(f,"([%w_]+)(.?)") do if d == "." then t[w] = t[w] or {}; t = t[w]; else t [w] = v;        end    endendsetfield("txy",10);print< /span>(txy);print(getfield("txy"));

< pre class="prettyprint">< span class="hljs-comment">–使用rawset绕过__newindex,给_G赋值,但是declare要在setmetatable调用前定义function declare(name,initval) rawset(_G,name,initval or false);endsetmetatable(_G,{ __newindex = function(_,n) error(“attempt to write to undeclared variable “..n,2); end, __index = function(_,n) error(“attempt to read undeclared variable “..n,2); end, })declare “a”;a = 1;print(a);

local declaredNames = {};function declare(name,initval)    rawset(_G,name,initval);    declaredNames[name] = true;endsetmetatable(_G,{    __newindex = function(t,n,v)        if not declaredNames[n] then            error("attempt to write to undeclared var. "..n,2);        else            rawset(t,n,v);        end    end,    __index = function(_,n)        if not declaredNames[n] then            error("attempt to read undeclared var. "..n,2);        else            return nil;        end    end,    })

39.可以使用setfenv函数来改变一个函数的环境。 Setfenv接受函数和新的环境作为参数。除了使用函数本身,还可以指定一个数字表示栈顶的活动函数。数字1代表当前函数,数字2代表调用当前函数的函数。

a = 1;local newgt = {};setmetatable(newgt,{__index = _G});--由于使用的是Lua5.3版本,所以用_ENV来代替setfenvlocal _ENV = newgt;a = 10;print(a);print(_G.a);_G.a = 20;print(_G.a)--由于使用的是Lua5.3,所以用load来代替loadstringload([[print(a)]],"tempload","t",_ENV)();

Leave a Comment

Your email address will not be published.