Lua metatable and _index
Chinese Blog Explanation:
Http://www.cnblogs.com/simonw/archive/2007/01/17/622032.html
Metatable:http://www.lua.org/pil/13.html
Table, some of the common methods are missing, using metatable to define these default methods for the table:
Add, Sub, mul, Div, mod, pow, UNM, concat, Len, eq, lt, le, ToString, GC, index, NEWINDEX, call ...
__index:http://www.lua.org/pil/13.4.1.html
If there is no such element in the Access table, the query metatable whether there is __index, if any, gets the result of _index call, and returns nil if there is no __index
__newindex:http://www.lua.org/pil/13.4.2.html
When setting a key that does not exist in the table, the __newindex that invokes metatable is triggered, and if no __newindex is set to the property on the target table, it is executed if there is a __newindex.
Example:
__index __newindex Comparison:
LocalBird = {Canfly =true}functionbird:new ()Localb = {} setmetatable(b, self) Self.__index= Self--Self.__newindex = Self returnbEndLocalOstrich = Bird:new ()--Bird.canfly is True, Ostrich.canfly is trueOstrich.canfly =false --Bird.canfly is True, Ostrich.canfly is falsePrint("ostrich.canfly="..ToString(ostrich.canfly))Print("bird.canfly="..ToString(Bird.canfly))
Other Test experiments:
--Define 2 TablesA = {5,6}b= {7,8}--use C to do metatable .c = {}--Redefining addition OperationsC.__add =function(OP1, OP2) for_, iteminch Ipairs(OP2) Do Table.insert(OP1, item)End returnOP1End--Custom MethodsC.Print=function() Print("C print!");End--set the metatable of A to C, error, print nil NOK--[[Setmetatable (A, C) a.print ()]]--set the metatable of A to C and call the built-in function defined by C OK--D now looks like {5,6,7,8}--[[Setmetatable (A, c) d = A + bfor _, item in Ipairs (d) do print (item) End]]--set the __index of A to C, you can call the C-defined print OK--[[Setmetatable (A, {__index = c}) a.print ()]]--set the metatable of A to C, you can call the C-defined print OK--[[C.__index = Csetmetatable (A, C) a.print ()--]]--The __index of a cannot be copied directly to C, error, NOK--[[A.__index = Ca.print ()--]]--set the __index of A to C, error a cannot perform the calculated operation, NOK--[[Setmetatable (A, {__index = c}) d = A + bfor _, item in Ipairs (d) do print (item) End]]--set the __add of A to the __add of C, OK--[[Setmetatable (A, {__add=c.__add}) d = A + bfor _, item in Ipairs (d) do print (item) end--]]--You can call a custom method, and the built-in method OK--[[Setmetatable (A, {__index = c, __add=c.__add}) a.print () d = A + bfor _, item in Ipairs (d) do print (item) end--]]
Lua metatable and _index experiments