Daily Lua (4)-deep Functions

Source: Internet
Author: User

1. The function is the first value in Lua.

In Lua, functions can be stored in variables and tables as numbers and strings, and can also be passed as parameters or return values of functions.

2. Lexical domain

A function can access the variables of an external function.

3. Anonymous Functions

Functions are anonymous like all other values, that is, they do not have a name. We can regard a function as a value. It can be assigned to a variable.

foo=function ( x )return 2*xendprint(foo(2))

4. Passing functions as parameters

There is a sort function in the table, which accepts a table value and a function as the parameter. For example:

classmate={{name="Jack",grade="90"},{name="Rose",grade="80"},{name="Tomas",grade="88"},{name="Mary",grade="60"}}foo=function ()    for k,val in ipairs(classmate) do   print(val.name.."-"..val.grade)endendprint("Before sort:")foo()print("SortByName:")table.sort(classmate,function(a,b) return(a.name)>b.name end)foo()print("SortByGrade:")table.sort(classmate,function(a,b) return(a.grade)>b.grade end)foo()

Running result:

At this time, the anonymous function shows great convenience.

Let's look at another example and evaluate the function.

The derivative is defined as (f (x + d)-f (x)/D, where D tends to be infinitely small. The following is the implementation of Lua.

function derivative( f,delta )delta=delta or 1e-4return function(x)return(f(x+delta)-f(x))/deltaendendc=derivative(math.sin)print(math.cos(10),c(10))


I feel a little confused --

5. Closed Functions
If a function is written in another function, the internal function can access local variables in the external function. This feature is called a "lexical domain ".

Example of a counter:

function newCounter()local i=0return function()i=i+1return iendendc1=newCounter()print(c1())print(c1())print(c1())

For the anonymous function in newcounter, I is a non-local variable used to keep a counter. When the anonymous function calls I, it seems that it is out of the range, in fact, Lua will correctly handle this situation with the concept of closure. This is the closure. To put it simply, a closure is a function that adds all "non-local variables" in the orientation required by the function ". If newcounter is called again, it will create a new local variable I to get a new closure.

Next, execute the following statement in the above program:

c2=newCounter()print(c2())print(c2())

C1 and c2 are two different closure created by a function. They have independent instances of local variable I.

6. Non-global functions

A non-global function refers to a function as a common variable, such as an integer or string. Store it in the table field and local variables. For example:

Lib={}Lib.add=function(x,y) return x+y endLib.mul=function(x,y) return x-y endprint(Lib.add(1,2))print(Lib.mul(3,100))

Another example of recursive call

--local fact=function(n)local function fact(n)if n==0 then return 1else return n*fact(n-1)endendprint(fact(100))

The line commented is an error message, because the fact is not defined during recursive calling, and the latter is correct.

7. Correct end call

The End call is similar to a goto function call. When a function calls the last action of another function, the call is considered the end call.

For example, F has nothing to do after calling g.

function f(x) <some operation> return g(x) end

The final call mechanism in Lua is that after the final call is determined to be the final call, the original function does not need to be returned after the final call function is executed, and the program does not need to save any stack information about the function, it does not consume any stack space. In Lua, it is called tail call elimination.

A very large application called at the end is a finite state machine. It can jump from this state to a state, and then it can jump infinitely without considering stack overflow. Is it great!

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.