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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。