Lua notes-meta-tables and meta-methods

Source: Internet
Author: User

A meta-table can be used to modify the behavior of a value so that it performs a specified action when confronted with a non-predefined operation. When Lua tries to add two tables, it checks whether one of the two has a meta-table, and then checks if there is a field called __add in the original table.

LUA does not create a meta table when it creates a new table, and you can use setmetatable to set or modify any table's meta-tables.

In Lua, you can only set the table's meta-table, and to set a meta-table of other types of values, you must do so through C code. Other types do not have a meta-table by default.

1. The meta-method of arithmetic class

set = {}local mt = {}--Create a new collection based on the values in the parameter list function set.new ( l ) Local  set = {}setmetatable (SET, MT)--sets MT to the currently created table's meta-table for _, v in ipairs ( L)  do set[v] = true endreturn set endfunction set.union ( a,  b ) Local res = set.new{}for k in pairs (a)  do res[k] =  True end for k in pairs (b)  do res[k] = true end return  resendfunction set.intersection ( a, b ) local res = set.new{}for  K in pairs (a)  do res[k] = b[k] end return res endfunction  set.tostring ( set ) local l = {}for e in pairs (Set)  do  l[#l  + 1] = e end return  "{"  .. Table.concat (l,  ", ")     "}"--table.coThe NCAT function connects all the strings in the given list and returns the connection result Endfunction set.print ( s ) print (set.tostring (s)) ends1 =  set.new{1, 2, 3, 4}s2 = set.new{2, 5}--Two collections have an identical meta-table print (Getmetatable (S1) )-->table: 0x7fee11c09940print (getmetatable (S2))-->table: 0x7fee11c09940--the meta-method into the meta-table. mt.__add = set.union --when Lua tries to add two sets, it calls the Set.union function and passes two operands as arguments s3 = s1 +  s2set.print (S3)-->{1, 2, 3, 4, 5}--similar, you can also use multiplication sign to find the intersection of collections mt.__mul =  Set.intersection set.print ((S1 + S2)  * s1)-->{1, 2, 3, 4}--[[in the meta table, Each arithmetic operator has a corresponding field name. In addition to __add  and __mul, there are __sub (subtraction), __div (division), __UNM (inverse number), __mod (modulo), and __pow (UP). In addition, you can define the __concat field, which describes the behavior of the join operator. ]]


2, the meta-method of the Relationship class

Mt.__le = function (A, b)--The set contains a for k in pairs (a) doif not b[k] then return False end end return TRUEENDMT.__LT = Functio N (A, B) return a <= B and not (b <= a) Endmt.__eq = function (A, b) return a <= B and b <= a ends1 = set.new {2, 4}s2 = set.new{2, 4, 8}print (S1 <= S2)-->trueprint (S1 < S2)-->trueprint (S1 >= S2)-->falseprint (S1 &G T S2)-->falseprint (S1 = = S2 * S1)-->true


3. Meta-method for table access

--[[when accessing a field that does not exist in a table, the interpreter is prompted to find a meta-method called __index. Without this meta-method, the access result is nil, otherwise the meta-method will provide the final result. ]]window = {}--Creates a namespace-uses default values to create a prototype Window.prototype = {x=0, y=0, width=100, height=200}window.mt = {}--Create a meta-table-- The Declaration constructor function window.new (o) setmetatable (o, window.mt) return oend--defines the __index meta method window.mt.__index = function (table, Key) return Window.prototype[key]end--__index does not have to be a function, it can also be a table--window.mt.__index = window.prototype--creates a new window and queries a field it does not have w = Window.new{x = ten, y = 20}print (w.width)-->100

The __newindex meta-method is similar to the __index meta-method, except that the former is used for table updates, while the latter is used for table queries. When you assign a value to an index that does not exist in a table, the interpreter looks for the __newindex meta method. If there is a meta-method, the interpreter invokes it instead of performing the assignment.




Lua notes-meta-tables and meta-methods

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.