【Lua高级教程】什么是Metatable举例说明

什么是Metatable

metatable是Lua中的重要概念,每个table均可以加上metatable,以改变相应的table的行为。函数

Metatables举例

lo_table =lo_meta_table =(lo_table)

上边的代码也能够写成一行,以下所示spa

-- setmetatable函数的返回值,就是该函数的第一个参数lo_table = setmetatable({}, {})

建立复杂的元表变量

metatable能够包括任何东西,metatable特有的键通常以__开头,例如__index__newindex,它们的值通常是函数或其余table。3d

lo_table = setmetatable({}, {
  __index = function(lo_table, key)    if key == "foo" then      return 0    else      return table[key]    end  end})

__index

  这是metatable最经常使用的键了。code

  当你经过键来访问table的时候,若是这个键没有值,那么Lua就会寻找该table的metatable(假定有metatable)中的__index键。若是__index包含一个表格,Lua会在表格中查找相应的键。ip

-- 建立元表变量lo_meta_table = { name = "蓝鸥" }-- 设置该元表变量做为关系变量的lo_table = setmetatable({}, { __index = lo_meta_table })-- 打印lo_table变量的姓名 蓝鸥print(lo_table.name)-- 打印lo_table变量年龄 nilprint(lo_table.age)

  若是__index包含一个函数的话,Lua就会调用那个函数,table和键会做为参数传递给函数。字符串

-- 建立元表变量lo_meta_table = { 
    name = "蓝鸥" ,
    action = function ( param )        -- body        if(param == "学生") then            print("让教育回归本质")        else            print("让蓝鸥维护教育")        end    end}-- 设置该元表变量做为关系变量的lo_table = setmetatable({}, { __index = lo_meta_table })-- 打印lo_table变量的动做 让教育回归本质print(lo_table.action("学生"))-- 打印lo_table变量的动做 让蓝鸥维护教育print(lo_table.action("肖浩"))-- 打印lo_table变量年龄 nilprint(lo_table.age)

 

__newindex

相似__index__newindex的值为函数或table,用于按键赋值的状况。get

-- 建立元表变量lo_meta_table = {}-- 设置该元表变量做为关系变量的lo_table = setmetatable({}, { __newindex = lo_meta_table })-- 设置lo_table变量的name关键字的值lo_table.name = "蓝鸥"-- 打印lo_meta_table元表变量name关键字的值值print(lo_meta_table.name)-- 打印lo_table变量name关键字的值print(lo_table.name)

 

-- 建立元表变量lo_meta_table = {}-- 设置该元表变量做为关系变量的lo_table = setmetatable({}, { __newindex = function(t, key, value)    if type(value) == "number" then      rawset(t, key, value * value)    else      rawset(t, key, value)    end  end})-- 设置lo_table变量的name关键字的值lo_table.name = "蓝鸥"-- 设置lo_table变量的age关键字的值lo_table.age = 3-- 打印lo_meta_table元表变量name关键字的值值print(lo_meta_table.name)-- 打印lo_table变量name关键字的值print(lo_table.name)-- 打印lo_meta_table元表变量age关键字的值值print(lo_meta_table.age)-- 打印lo_table变量age关键字的值print(lo_table.age)

上面的代码中使用了rawgetrawset以免死循环。使用这两个函数,能够避免Lua使用__index__newindexstring

运算符

利用metatable能够定义运算符,例如+io

-- 建立重载+号行为的表变量lo_table = setmetatable({ 1, 2, 3 }, {
  __add = function(lo_table, other)
    new = {}    -- 遍历元素加other    for _, v in ipairs(lo_table) 
        do table.insert(new, v + other) 
    end    return new  end})-- 进行计算+lo_table = lo_table + 2-- 打印获得的结果print(lo_table[1])print(lo_table[2])print(lo_table[3])

__index__newindex不一样,__mul的值只能是函数。与__mul相似的键有:table

  • __add (+)

  • __sub (-)

  • __div (/)

  • __mod (%)

  • __unm 取负

  • __concat (..)

  • __eq (==)

  • __lt (<)

  • __le (<=)

 

__call

__call使得你能够像调用函数同样调用table

t = =  (a + b + c) *, , , )

 

__tostring

最后讲下__tostring,它能够定义如何将一个table转换成字符串,常常和 print 配合使用,由于默认状况下,你打印table的时候会显示 table: 0x7f86f3d04d80 这样的代码

lo_table = setmetatable({ 1, 2, 3 }, {
  __tostring = function(lo_table)
    sum = 0    for _, v in pairs(lo_table) 
    do 
        sum = sum + v 
    end    
    return "计算的结果是: " .. sum  end})-- prints out "计算的结果是: 6" print(lo_table)

 

建立一个简单的向量Vector类

Vector = {}
Vector.__index = Vectorfunction Vector.new(x, y)  return setmetatable({ x = x or 0, y = y or 0 }, Vector)end-- __call关键字setmetatable(Vector, { __call = function(_, ...) return Vector.new(...) end })-- + 运算符function Vector:__add(other)  -- ...     local result = Vector(self.x + other.x,self.y + other.y)     return resultend-- __tostring关键字function Vector:__tostring()    -- body    return "x: " .. self.x .. " y: " .. self.yenda = Vector.new(12, 10)
b = Vector(20, 11)
c = a + bprint(a)print(c)
相关文章
相关标签/搜索