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