lua--3. meta-table metatable

Source: Internet
Author: User
Tags lua

Lua's metatable is also a common table, and LUA provides metatable functionality, primarily for several functions:
    1. Controlling access to a table
    2. Providing support for the LUA function library
    3. Overloading the behavior of arithmetic and relational operators

      1. Using MetaTable to control access to the table

      When querying a table's key, if the table's key does not have a value, then Lua looks for the __index element method in the table's metatable: If __index points to a Table,lua it finds the corresponding key in the table, and , __index can also point to a method

When assigning a key to a table, if the table exists that field is assigned a value, and if not, then Lua looks for the __newindex element method in the table's metatable: If __newindex points to a table, LUA assigns the table an operation, and if __newindex points to a method, Lua calls the method

__index meta-method in Lua
If __index contains a table, Lua looks for the corresponding key in this table.
Also, __index can point to a table or point to a method __index when it points to a table:
Before we need to know when we look for an element in a table
First look in the table, then return the corresponding value, none to see if the table has a meta-table metatable
Nil if no meta-table is returned
When there is a meta-table, LUA does not look in its meta-table, but instead finds it in the __index field of its meta-table
Therefore: only use the Setmetatable () method to set the meta-table, and cannot get the elements in the corresponding meta-table
BaseClass = {theKey1 = "the string value1"}--[[DerivedClass = {}setmetatable(DerivedClass,BaseClass)]]----注释的两句可简写为:DerivedClass = setmetatable({},BaseClass)res = DerivedClass.theKey1print(res)

After setting the __index key for the corresponding meta table:

BaseClass = {theKey1 = "the string value1"}BaseClass.__index = BaseClassDerivedClass = setmetatable({},BaseClass)res = DerivedClass.theKey1print(res)

You can also change a shorthand method:

BaseClass = {theKey1 = "the string value1"}DerivedClass = setmetatable({},{__index = BaseClass})    --即直接设  AnonymousTable = {__index = BaseClass} 为DerivedClass的元表,查找时可直接在AnonymousTable中的__index域对应的表BaseClass中查找res = DerivedClass.theKey1print(res)

Therefore, the inheritance in Lua can be expressed as:

local Car = {}Car.__index = Carfunction Car:new(o)    o = o or {}    setmetatable(o,Car)    return oendfunction Car:run()    print("Car‘s run func.")end--直接调用“父类”中的run方法Car.run()local FordCar = Car:new()--子类调用“父类”中的run方法FordCar.run()--重写fordCar中的run方法function FordCar:run()    print("FordCar‘s run func.")end--重写之后调用FordCar.run()
When __index points to a method
When __index points to a method, Lua attempts to call the __index meta method Metamethod (__index Metamethod can accept two parameters table and key) when we access the nonexistent domain of the table.
local t1 = {}t1.__index = function(table,key)    print("call the __index metamethod")    print("table"..tostring(table))    print("key"..key)    return key.." from the __index"end--set t1 as t2‘s metatablelocal t2 = setmetatable({},t1)--pass the table and the key to __indexmetamethodlocal res = t2.key1print("the result is :"..res)print("------------------")res = t2.key2print("the result is :"..res)

__newindex Meta-method
If you assign a value to a nonexistent field in the table, Lua checks for __newindex Metamethod:

1. If __newindex is a function, Lua will call the function instead of the assignment (if __newindex is a function, it can accept three parameters table key value. You can call Rawset (t, K, V) if you want to ignore the __newindex method to assign a value to a table's field
2. If __newindex is a table,lua, this table will be assigned a value

--file:newindex.lualocal mt = {    key1 = "key1‘s value"}local other = {    key1 = "the old value"}mt.__index = mt--[[mt.__newindex = function()    print "Can not set value"end--]]mt.__newindex = other local t = setmetatable({},mt)t.key1 = "the new value from the table t."print(t.key1)--对__newindex指向的table中的key1进行更新操作,但是table t 中仍然没有键key1,进行t.key1的查询时,查询的仍然是__index中对应的键key1的值print(other.key1)

2. Providing support for the LUA function library

The Lua library can define and use Metamethod to accomplish some specific operations
A typical example is the __tostring function in the Lua base library, which is called by the print function to output, and when you call print, the __tostring is checked and called Metamethod

--file:tablelib.lualocal mt = {}mt.__tostring = function(t)    return ‘{‘..table.concat(t,‘,‘)..‘}‘endlocal t = {1,2,3}print(t)print("-----------------")setmetatable(t,mt)print(t)

3. Behavior of overloaded arithmetic and relational operators

lua--3. meta-table metatable

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.