Introduction to the closure function of the Lua Advanced tutorial, and an example of a meta table _lua

Source: Internet
Author: User
Tags closure inheritance lua

Copy Code code as follows:

function Createcountdowntimer (second)
Local Ms=second * 1000;
Local function Countdown ()
ms = Ms-1;
return MS;
End
return countdown;
End

Timer1 = Createcountdowntimer (1);
For i=1,3 do
Print (Timer1 ());
End
Print ("------------");
Timer2 = Createcountdowntimer (1);
For i=0,2 do
Print (Timer2 ());
End


Copy Code code as follows:

999
998
997
------------
999
998
997

upvalue: a function used to define a local variable (external localvariable) that is outside its function body is called the upvalue of this function.

In the previous code, the local variable MS used by the function countdown in the function Createcountdowntimer is the upvalue of Countdown, but MS is only a local variable for Createcountdowntimer, Not upvalue. Upvalue is a unique attribute of Lua that differs from C + +, and needs to be carefully understood in conjunction with code.

function Closure: A function and all the upvalue it uses constitute a function closure.

A closure is an intrinsic function that accesses external local variables of one or more external functions. These external local variables hold their values (state) after each closure's successful invocation. Of course, if you want to create a closure, you must create its external local variables. So a typical closure structure consists of two functions: one is the closure itself; the other is the factory (the function that creates the closure). The iterator needs to keep the state of the last successful call and the state of the next successful call, which is where he knows where he is going and where he will go. The mechanism provided by the closure can be easily accomplished by this task.

A comparison of the LUA function closures with the C function: The LUA function closure makes a function capable of maintaining its own state, which in this sense can be analogous to a C function with a static local variable. But the two are significantly different: for Lua, a function is a basic data type--represents an (executable) object that can have its own state, but for a C function with a static local variable, it is not a data type of C, nor does it produce any object instances, it is simply a symbolic name for a static address.

Object-based implementation methods

Copy Code code as follows:

function Create (NAME,ID)
Local data={name = Name,id=id};
Local obj={};
function obj. GetName ()
return data.name;
End
function obj. GetID ()
return data.id;
End
function obj. SetName (name)
Data.name=name;
End
function obj. SetID (ID)
Data.id=id
End
return obj;
End

O1 = Create ("Sam", 001)
O2 = Create ("Bob", 007)
O1. SetID (100)
Print ("O1 ' s ID:", O1.) GetID (), "O2 ' s ID:", O2. GetID ())
O2. SetName ("Lucy")
Print ("O1 ' Name:", O1.) GetName (), "O2 ' s Name:", O2. GetName ())

--o1 ' s id:100 O2 ' s Id:7
--o1 ' s Name:sam O2 ' s Name:lucy

implementation: the need to hide the members in a table, which is a member function of the upvalue.
limitations: object-based implementations do not involve inheritance and polymorphism. On the other hand, whether script programming requires inheritance and polymorphism depends on the situation.

Wenzu

Copy Code code as follows:

t = {}
m = {a = "and", B = "Li Lei", c = "Han Meimei"}
Setmetatable (t, {__index = m})--table {__index=m} as Wenzu of table T
For K, v. in pairs (t) do--exhaustive table t
Print (v)
End
Print ("-------------")
Print (t.b, T.A, t.c)

--Output results
---------------
--li Lei and Han Meimei

function Add (t1, T2)
--' # ' operator takes table length
ASSERT (#t1 = = #t2)
Local length = #t1
For i = 1, length do
T1[i] = T1[i] + t2[i]
End
return T1
End
--setmetatable returns the table being set
T1 = setmetatable ({1, 2, 3}, {__add = add})
T2 = setmetatable ({Ten,}, {__add = add})

T1 = t1 + t2
For i = 1, #t1 do
Print (T1[i])
End
--11
--22
--33

definition: the meta table itself is just a normal table, set to an object by a specific method (such as setmetatable), which affects the behavior of the object, and what behavior an object has affected by the meta table and how those actions are affected are constrained by the Lua language. For example, in the previous code, the addition of two table objects, if not the intervention of the meta table, is an error; but Lua prescribes that the meta table can "overload" the addition operator of an object, so if you set the meta table that defines the addition operation to the two tables, they can add. Wenzu is one of the most critical concepts in Lua and rich in content, please refer to the LUA documentation for more information.

comparison between a meta table and a C + + virtual table: If you compare a table to an object, the meta table is a "meta" object that can change the behavior of the object. In a way, the meta table can be compared with C + + virtual table. But the two are very different: the meta table can be changed dynamically, C + + virtual table is static; the meta table can affect many aspects of the behavior of tables (and other types of objects), and the virtual table is primarily to locate the object's virtual method (up to a little rtti).

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.