Go Lua meta-table

Source: Internet
Author: User

Each value in Lua has a meta-table, and talble and UserData can have separate meta-tables, while other types of values share the singleton table that their type belongs to. LUA does not create a meta table when it creates a table.

T = {}print (getmetatable (t))  -- shows that the meta-table is nil at this time-- You can use setmetatable to set or modify any table's meta-table T1 = {}setmetatable(t,t1)assert (getmetatable (t) = = T1)        

Any table can be a meta-table of any value, and a set of related tables can share a common meta-table that describes a common behavior. A tabel can even be used as its own meta-table to describe its unique behavior.

In Lua, you can only set the table's meta tables. To set other types of meta-tables, you must do so by using C code

Print (getmetatable ("hi"))  --The005DECD8 description string has a meta-table print (getmetatable (-- Number has no meta-table         
13.1 meta-Methods of arithmetic classes
Set = {}--CollectionLocal MT = {}--Collection Meta table--Create a new collection based on the values in the parameter listfunctionSet.new (L)Local set ={}Setmetatable (SET,MT)--Specifies that the metatable of the table set is MTFor K,vInchIpairs (L)DoSET[V] =True--Take strands as data.EndReturnSetEndfunctionSet.union (A, B)Local res =set.new{}For K,vInchPairs (a)Do res[k] =TrueEndFor K,vInchPairs (b)Do res[k] =TrueEndReturnResEndfunctionSet.intersection (A, B)Local res =set.new{}For K,vInchPairs (a)DoIf B[K]ThenRES[K] =TrueEndEndReturnResEndfunction Set.Tostring(set)Local L ={}For K,vInchPairs (set)Dol[#l +1] =KEndReturn"{" ..Table.concat (L,",") .."}"Endfunction Set.Print(s)Print (Set.Tostring(s))End--Adding meta-methods to the meta-table Mt.__add = Set.union--Specify the plus sign as the method for the Mt.__mul = set.intersection--Specify a method for intersection of multiplication signs1 = Set.new{11,22,< Span style= "color: #800080;" >31,44,56}S2 = Set.new {66,33,22,31}S3 = s1 + s2 -- set Set . print (S3) -- output {11, 31, 44}S4 = S1 * s2 -- intersection Set.print (S4) -- output {--]      
13.2 Relationship Class Element method

Relationship refers to __eq (equals), __lt (less than), etc.

Mt.__le =function(A, B)For KInchPairs (a)DoIfNot B[k]ThenReturnFalseEndEndReturnTrueEndMt.__lt =function(A, B)Return a<=bandNot (b<=AEndMt.__eq =function(A, B)Return a<=band b<=AEndSS1 = set.new{2,4}ss2 = set.new{< Span style= "color: #800080;" >4,10,2}print (SS1<=SS2) --true print (SS1<SS2) -- Trueprint (SS1>=SS1) -- trueprint (SS1>SS1) --falseprint (SS1 = = SS2*SS1) --true       
13.3 meta-Methods for library definitions

ToString is a typical example. It can represent various types of values as simple text formats

----TABLE:003ECEF0

The function always calls ToString to format the output. When any value is formatted, ToString detects whether the value has a __tostring element method. If so, he calls this method, which is used as the return value of ToString.

In the collection instance, we have decided on the method of representing the appointment as a string, and we can set the __tostring field of the meta-table

mt.__tostring = Set. ToString
Sstext = set.new{,6666}print (sstext)  ----- -------  

Suppose you want to protect the meta-table of a collection so that users cannot see or modify the collection's meta-tables. Then we need to use the __metatable. When the field is set, Getmetatable returns the value of the field, and Setmetatable throws an error

' Notyour business'sstext1 = set.new{}  Print (-notyour businesssetmetatable (S1 ,{})
13.4 Table Access meta-method 13.4.1 __index meta-method

When accessing a field that does not exist in a table, nil is obtained if the field does not exist, but if the table has a meta-method __index then the meta-method will provide the result if there is no such field.

Window ={}window.prototype = {x=0,y=0,width =100,height =100}WINDOW.MT ={}function Window.new (o) setmetatable (O,WINDOW.MT) return Oend-- now defines a meta method window.mt.__index = function (Table,key) return Window.prototype[key]endw = Window.new{x=10,y= 20}print (W.width) Span style= "color: #008000;" >--       

The __index meta method can also be a table

13.4.2 __newindex Meta-method

Unlike __index, __index is used at the time of the query and _newindes is used at the time of the update.

13.4.3 table with default values

The following code sets the default value for table

function SetDefault (t,d)    endsetmetatable(T,MT)end    
13.4.4 Tracking Table Access

__index and __newindex do not work without the required index in the table. Because only table remains empty to capture all access to him, to monitor all access to a table you have to create a proxy for the real table

T_SRC = {}--The table to trackLocal_t =T_SRCT = {}--Create an agent--Create a meta tableLocal MT ={__index =function(t,k)Print"*access to Element" ..Tostring(k))Return_tKEnd, __newindex =function(T,K,V)Print"*update of Element" ..tostring (k)..  " to ". tostring (v) _t[k] =< Span style= "color: #000000;" > v end}setmetatable< Span style= "color: #000000;" > (T,MT) T[2] = hello< Span style= "color: #800000;" > "-- *update of element 2 to Helloprint (T[2]) --* Access to Element 2              
13.4.5 Read-only table

Read-only table is similar to the previous section tracking table, which restricts the modification of table memory by __newindex

Go Lua meta-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.