Lua:元表(metatable)与元方法(meatmethod)

  local _a1 = {20,1,key1 = "hello",key2 = "world",lang = "lua"}
  local _a2 = {key1 = "hello",key2 = "world"}

  print("a2的Metatable:",getMetatable(_a2))

  setMetatable(_a2,{__index = _a1})
  for _,v in pairs(_a2) do
      print(v)
  end

  print("a2的Metatable:",getMetatable(_a2))

  for k,v in pairs(getMetatable(_a2))do
	print(k,v)
	for i,j in pairs(v)do
		print(i,j)
	end
  end

a2的Metatable: nil
hello
world
a2的Metatable: table: 003CBB20
__index table: 003CAC60
1 20
2 1
key1 hello
lang lua
key2 world

--算术类元方法:字段:__add  __mul  __ sub  __div  __unm  __mod  __pow  (__concat)
--代码:(两个table相加)
tA = {1,3}
tB = {5,7}

--tSum = tA + tB

mt = {}

mt.__add = function(t1,t2)
    for k,v in ipairs(t2) do
        table.insert(t1,v)
    end
	return t1
end

setMetatable(tA,mt)

tSum = tA + tB

for k,v in pairs(tSum) do
    print(v)
end

1
3
5
7

--关系类元方法: 字段:__eq __lt(<) __le(<=),其他Lua自动转换 a~=b --> not(a == b) a > b --> b < a a >= b --> b <= a 【注意NaN的情况】
--代码:
mt = {}
function mt.__lt(tA,tB)
    return #tA < #tB
end

tA,tB = {3},{1,2}

setMetatable(tA,mt)
setMetatable(tB,mt)
print(tA < tB)

true
 

--用__index/__newindex来限制访问

function cannotModifyHp(object)
    local proxy = {}
    local mt = {
        __index = object,__newindex = function(t,k,v)
        if k ~= "hp" then
        object[k] = v
        end
    end
    }
    setMetatable(proxy,mt)
    return proxy
end

object = {hp = 10,age = 11}
function object.sethp(self,newhp)
    self.hp = newhp
end

o = cannotModifyHp(object)

o.hp = 100
print(o.hp)

o:sethp(100)
print(o.hp)

object:sethp(100)
print(o.hp)

10
10
100

Window = {}
Window.prototype = {x = 0,y = 0,width = 100,height = 100,}
Window.mt = {}

function Window.new(o)
    setMetatable(o,Window.mt)
    return o
end

Window.mt.__index = Window.prototype

Window.mt.__newindex = function (table,key,value)
    if key == "wangbin" then
        rawset(table,"wangbin","yes,i am")
    end
end

w = Window.new{x = 10,y = 20}
w.wangbin = "55"
print(w.wangbin)

yes,i am

相关文章

1.github代码实践源代码是lua脚本语言,下载th之后运行thmai...
此文为搬运帖,原帖地址https://www.cnblogs.com/zwywilliam/...
Rime输入法通过定义lua文件,可以实现获取当前时间日期的功能...
localfunctiongenerate_action(params)localscale_action=cc...
2022年1月11日13:57:45 官方:https://opm.openresty.org/官...
在Lua中的table(表),就像c#中的HashMap(哈希表),key和...