A brief analysis of closure (closure) in Lua _lua

Source: Internet
Author: User
Tags anonymous closure lua

Before the closure of a smattering of knowledge, on the internet can not find an article to make it clear, today seems like the first time to it a little clear understanding, write a blog to remember

The LUA function is a first-class Value thing, what is it?
Is that they are no different from the traditional type of change.
Can be stored in a variable,
Can be stored in a table,
can be passed as arguments to other functions,
Can be a return value for another function.

They also have a specific lexical domain (lexical scoping), in other words, a function can be nested within another function, and internal functions can access variables in external functions.
As in the following example:

Copy Code code as follows:

function test (x)
return function (value)
return value * x
End
End

Func = Test (10)

Print (func (11))


In Test (), an anonymous function is nested as the return value, and an external value variable can be accessed in this anonymous function
Let's look at another example.
Copy Code code as follows:

function Newcounter ()
Local i = 0
Func = function ()
i = i + 1
return I
End

return func
End

c = Newcounter ()
Print (c ())
Print (c ())

C1 = Newcounter ()
Print (C1 ())
Print (C1 ())


In the code, a "non-local variable" I is accessed in the function Func to hold a counter
Initially, because the function newcounter that created the variable i has been returned, each call to Func should be more than the scope

In fact, LUA deals with this situation with a closure concept.
A closure is a function plus all the "nonlocal variables" that the function needs to access.

So in the example above C1, C2 is the two different closure created by the same function, each owning a separate instance of the local variable i.

Technically, there is only closure in Lua, and there is no "function". Because "function" itself is a special kind of closure.

PostScript, C + + class objects can not also achieve similar effects?

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.