The sixth chapter: re-discussion function
The functions in Lua are the first class values (first-class values) with the word legal bounds (lexical scoping).
The first class of values means that functions and other values (numeric, string) in Lua can be stored in a variable
can also be stored in a table, as a function parameter, and as a function return value.
Word legal boundaries : A nested function can access variables in his external function. This feature provides Lua with a
Powerful programming capabilities.
Let's take a look at some examples of how Lua's functions can be assigned as parameters as normal variables ...
functionFoo (x)returnX *2 EndPrint(Foo (3))--6a= {p =Print}A.P ("Hello World")--Hello WorldPrint=Math.sin --Print new Refer to the SIN functionA.P (Print(1)) Sin=a.p sin (Ten, -)--Ten Funciton PrintNetwork={{Name="Grauna", IP ="210.26.30.34"}, {name="arraial", IP ="210.26.30.23"}, {name="Lua", IP ="210.26.23.12"}, {name="Derain", IP ="210.26.23.20"}, }Table.sort(Network,function(A, B)return(A.name > B.name)End)--function anonymous function with no name1 closures
When another function is nested inside a function, the inner function body can access the local variables of the external function, which is called lexical definition.
Names = {"Peter","Paul","Mary"}grades={mary=Ten, paul=7, mary=5}Table.sort(Names,function(N1,N2)returnGRADES[N1] >Grades[n2]End)--Implement the above function functionfunctionSortbygrade (names,grades)Table.sort(Names,function(N1,N2)returnGRADES[N1] > GRADES[N2]--Compare the Grades End)End
An example of a counter:
functionNewcounter ()Locali =0 return function() I= i +1 returnIEndEndC1=Newcounter ()Print(C1 ())--1Print(C1 ())--2C2 =Newcounter ()Print(C2 ())--1Print(C1 ()) –3
Technically, a closure refers to a value rather than a function, and a function is simply a prototype declaration of a closure;
You can also use closures to implement function redefinition:
Print (math.sin(math.sinmath.sinfunction (x) return Math.PI the )endprint(math.sin)
2. Non-global functions
LUA functions can be used as global variables as well as local variables, functions using table scopes, there are three ways to define
--tables and functions are put togetherLib ={}lib.foo=function(x, y)returnX +yEndLib.goo=function(x, y)returnX-yEnd--using Table ConstructorsLib2={foo=function(x, Y)returnX + yEnd, Goo=function(x, Y)returnX-yEnd}--define the way threefunctionlib.square (x)return 2*xEndfunctionlib.sqrt (x)return math.sqrt(x)EndPrint(Lib.foo (2,3))Print(Lib2.goo (4,5))Print(Lib.square (2))Print(Lib.sqrt (3))
3, the correct tail call
Another interesting feature of the LUA function is the ability to handle tail calls correctly (proper tail recursion)
A tail call is a goto call similar to the end of a function, and we call this call a tail call when the last action of the function is to invoke another function.
For example:
function f (x) return g (x) End
Lua Advanced Chapter (i)