print("-------------------------__index方法--------------------------")
mytable = setmetatable({key1 = "value1"},{
__index = function(mytable,key)
if key == "key2" then
return "metatablevalue"
else
return nil
end
end
})
print(mytable.key1,mytable.key2)
print("\n----------------------------__newindex方法------------------------")
mymetatable = {}
mytable = setmetatable({key1 = "value1"},{__newindex = mymetatable })
print(mytable.key1)
mytable.newkey = "新值1"
print(mytable.newkey,mymetatable.newkey)
mytable.key1 = "新值2"
print(mytable.key1,mymetatable.key1)
print("\n-------------------------rawset-------------------------------")
mytable = setmetatable({key1 = "value1"},{
__newindex = function(mytable,key,value)
rawset(mytable,key,value)
end
})
mytable.key1 = "new value"
mytable.key2 = 4
print(mytable.key1,mytable.key2)
print("\n----------------------------添加操作符-----------------------")
function table_max(t)
local temp_val = 0
for k , v in pairs(t) do
if temp_val < k then
temp_val = k
end
end
return temp_val
end
mytable = setmetatable({3,5,6},{
__add = function(mytable,newtable)
for i=1 , table_max(newtable) do
table.insert(mytable,table_max(mytable)+1,newtable[i])
end
return mytable
end
})
secondtable = {7,8,9}
mytable = mytable + secondtable
for k,v in ipairs(mytable) do
print(k,v)
end
print("\n-------------------__call元方法-----------------------------------")
--定义元方法__call
mytable = setmetatable({10},{
__call = function(mytable,newtable)
sum = 0
for i = 1, table_max(mytable) do
sum = sum + mytable[i]
end
for i = 1, table_max(newtable) do
sum = sum + newtable[i]
end
return sum
end
})
newtable = {10,15,15}
print(mytable(newtable))
print("\n-------------------__tostring元方法---------------------------------")
mytable = setmetatable({10,20,20},{
__tostring = function(mytable)
sum = 0
for k , v in pairs(mytable) do
sum = sum + v
end
return "表中所有元素的和为" .. sum
end
})
print(mytable)
运行结果: