例程
1 3
2 5
3 7
5
nil
9
5
nil
9
nil
2,3,4,
a = {1, 2, 3}
b = {2, 3, 4}
mt = {}
mt.__add = function(a,b)
local len = table.getn(a);
local res = {}
for i = 1, len do
res[i] = a[i] + b[i]
end
return res
end
setmetatable(a, mt)
setmetatable(b, mt)
c = a + b
for k, v in ipairs(c) do
print(k, v)
end
运行结果
1 3
2 5
3 7
__add (+)
__sub (-)
__mul (*)
__div (/)
__mod (%)
__pow (^)
__unm
__concat (..)
__len (#)
__eq (==)
__lt (<)
__le (<=)
__index (table[key])
__newindex (table[key] = value)
__call
__tostring (打印表中元素)
例程: __index
tab = {a = 5, b = 7}
tab.__index = function(t, key)
return tab[key]
end
tab.__newindex = function(t, key, val)
tab[key] = val
end
mytab = {}
setmetatable(mytab, tab)
print(mytab.a) -- 元素不存在时,将访问元表
print(rawget(mytab, a)) -- 判断表 mytab 中是否存在 a
mytab.test = 9 -- 这个值被存入元表,调用了 __newindex
print(mytab.test)
print(rawget(mytab, test))
运行结果
5
nil
9
nil
例程
tab = {a = 5, b = 7}
tab.__index = function(t, key)
return tab[key]
end
tab.__newindex = function(t, key, val)
tab[key] = val
end
tab.__tostring = function(t) -- 打印表 mytab 中的元素
local l = table.getn(t)
local s = ""
for i = 1, l do
s = s .. t[i] .. ","
end
return s
end
mytab = {2,3,4}
setmetatable(mytab, tab)
print(mytab.a) -- 元素不存在时,将访问元表
print(rawget(mytab, a)) -- 判断表 mytab 中是否存在 a
mytab.test = 9 -- 这个值被存入元表,调用了 __newindex
print(mytab.test)
print(rawget(mytab, test))
print(mytab)
运行结果
5
nil
9
nil
2,3,4,