Closure summary in Lua

Source: Internet
Author: User

function newcounter ()     local i=0    returnfunction()        i=i+1         return  i    endendC1=newcounter ()Print  (C1 ())print(C1 ())

The above code output
Closure = function + reference environment. The Newcounter function in the preceding code returns a function, and the returned anonymous function is the function in the part of the closure, and the reference environment is the environment where the variable I resides. In fact, closures are just like functions in form and expression, but actually not functions, and we all know that functions are a combination of some executable statements that are determined after the function is defined and no longer executed, so the function has only one instance. While closures can have multiple instances at run time, different reference environments and the same combination of functions can produce different instances, just like the same class code, which can create different class instances. When you look at someone else's article, you see that the child function can use a local variable in the parent function, which is called a closure!

Functions can be defined in LUA functions, which are inline functions, which can access all local variables that an external function has already created, and these variables are called the upvalue,upvalue of the inline function actually refer to variables rather than values, which can be shared between internal functions. such as the following code:

functionfun1 ()LocalVal=Ten    functionifunc1 ()Print(val)End    functionIfunc2 () Val=val+Ten    End    returnIFUNC1,IFUNC2EndLocala,b=fun1 () A ()--Output TenB () A ()--Output

function mypower (x)     return function (y)         return y^x    endendpower2=mypower (2) Power3 =mypower (3)print(Power2 (4))print( Power3 (5))

Closure summary in Lua

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.