The understanding function of Lua closure and several expression methods of table

Source: Internet
Author: User

The recent work is not very busy, so I learned some of the LUA knowledge, but only to see a two-hour encounter a problem-closures. Well, I saw it at first glance and thought it was about the balabala of close. (Forgive my ignorance)! But the more down to see the more confused, so on-line read a lot of masters writing things to learn, hereby record, so that later see not .... To be despised.

In Lua, functions are variables, can be stored in tables, can be parameters of functions, or return values, in fact, a LUA closure can be understood as a closure (function name) {Functional abstraction, Upvalue, env}, function abstraction is the function of the body,

Upvalue: is an inline function that accesses all local variables that the outsourced function has created, which are called external local variables of the inline function (external local variable) or Upvalue, Upvalue actually refers to a variable rather than a value .

function newcounter ()   Local 0   return function ()  1    return I    End End

In the example above, I is a upvalue

The simple saying closure is a function plus it can be correctly accessed by the Upvalue. Upvalue is a local variable of the outer function of a nested function. This function is generally defined inside another function, and he can access the member variables, parameters, and global functions defined within the external function. And this function can also return functions.

Tables and Functions

One:

Lib = {}

Lib.foo = function (x, y) retrun x+ y End

Lib.goo = function (x) Retrun x end;

Two:

Lib = {

Foo = function (x, y) retrun x+ y End

Goo = function (x) Retrun x end;

}

Three:

Lib = {}

Lib = {}

Functio Lib.foo (x, y) retrun x+ y End

function Lib.goo (x) Retrun x end;

The understanding function of Lua closure and several expression methods of table

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.