local t = {} -- 普通表t为空
local other = {foo = 2} -- 元表 中有foo值
setmetatable(t,{__index = other}) -- 把 other 设为 t 的元表__index
print(t.foo); ---输出 2
print(t.bar); ---输出nil
local t = {foo = 3 } -- 普通表t为空
local other = {foo = 2} -- 元表 中有foo值
setmetatable(t,{__index = other}) -- 把 other 设为 t 的元表__index
print(t.foo); ---输出 3
print(t.bar); ---输出nil
local t = {key1 = "value1" }
local function metatable(mytable,key)
if key == "key2" then
return "metatablevalue"
else
return nil
end
end
setmetatable(t,{__index = metatable})
print(t.key1);
print(t.key2);
print(t.key3);
local function add(mytable,newtable)
local num = table.maxn(newtable)
for i = 1, num do
table.insert(mytable,newtable[i])
end
return mytable
end
local t1 = {1,2,3}
local t2 = {4,5,6}
setmetatable(t1,{__add = add})
t1 = t1 + t2
for k,v in ipairs(t1) do
print("key=",k," value=",v)
end
local function call(mytable,newtable)
local sum = 0
local i
for i = 1, table.maxn(mytable) do
sum = sum + mytable[i]
end
for i = 1, table.maxn(newtable) do
sum = sum + newtable[i]
end
return sum
end
local t1 = {1,2,3}
local t2 = {4,5,6}
setmetatable(t1,{__call = call})
local sum = t1(t2)
print(sum)
local t1 = {1,2,3}
setmetatable(t1,{
__tostring = function(mytable)
local sum = 0
for k, v in pairs(mytable) do
sum = sum + v
end
return "all value sum =" .. sum
end
})
print(t1) ----print方法会调用table的tostring元方法