lua metatable Metatable (VI)

 

 

Metatable to understand more abstract, but it is a data structure lua set only, assuming table_A, table_B these two table, if table_A to operate table_B, obviously impossible 
because there is no relationship between those who are in, If the set has become table_a table_b element table, table_a table_b can operate inside the element, and even inside of the table element 2 
computes the operand table element 
disposed syntax: setmetatable (table_a, table_b) 
metatables there element method for the following: 
 . 1 .__ index - - this method is mainly used to access the table. 
   Metatable setting keys by which, table to get the value of this key by a metatable 
 2 .__ newIndex are - - This method is primarily table update. 
   When a table index to the assignment, the interpreter calls the lookup __newIndex method, if present, call assignment operation 
MyTable = {}; - Normal table 
mymetatable = {__metatable = " Hi " }; - metatables 
setmetatable(mytable, mymetatable); - the mymetatable element arranged mytable table 
mytable = setmetatable ({}, {}); - can also be written as 
getmetatable (mytable); - Returns mymetatable 

- the __index key as 

local table_a = {K1 = " the Hello " }
 local table_b = K2 = { " World " }
 setmetatable (table_a, the __index = { table_b})
 Print (table_A.k1)
 Print (table_A.k2) 

- the __index function is a 

function fun1 (Table , Key)
 Print (Table," \ N- " , Key)
  return  " Hello " 
End 
local table_a = {k1 = " World " } 

setmetatable (table_a, the __index = {} fun1) - will be passed as parameters k1 and table_a to fun1 
Print (table_A.k2) 



- - the Lua a table lookup rules element, in fact, three steps as follows: 
- - table 1. Analyzing there __index element method, if the method is __index nil, nil is returned; 
- - if __index the method returns a table is a table lookup step by 2.3 
- - 2. find the table, if found, return that element, could not find continued 
- - 3. To determine whether the table meta table, if there is no yuan table, return nil, meta table continues.

--- 2 .__ when newindex as key


local table_A = { k1 = "hi"}
local table_B = {}

 
 

table_A = setmetatable(table_A,{__newindex = table_B})
table_A.k1 = "hihi"
table_A.k2 = "haha"
print("修改后的是:",table_A.k1,table_A.k2,table_B.k2)

 
 

- __newindex is a function

function fun4(table,key,value)
print(table,"\n",key,value)
end
local table_A = {k1 = "hi"}

 
 

setmetatable(table_A,{__newindex = fun4 })

 
 

table_A.k2 = "Good"

 

 

Guess you like

Origin www.cnblogs.com/MrRightZhao/p/11301283.html