Lua使用元方法操作两个table元素进行加减乘
local mt = {}
mt.__add = function(mytable, othertable)
local temp = {}
for i,v in ipairs(mytable) do
temp[i] = v + othertable[i]
end
return temp
end
mt.__sub = function(mytable, othertable)
local temp = {}
for i,v in ipairs(mytable) do
temp[i] = mytable[i] - othertable[i]
end
return temp
end
mt.__mul = function(mytable, othertable)
local temp = {}
for i,v in ipairs(mytable) do
temp[i] = mytable[i] * othertable[i]
end
return temp
end
function show(mytable)
for i,v in pairs(mytable) do
print("table["..i.."] = "..v)
end
print('--分割线--')
end
function main()
local mytable = {1,2,3}
setmetatable(mytable, mt)
local secondtable = {20,30,50}
local newtable = mytable + secondtable
show(newtable)
local newtable = mytable - secondtable
show(newtable)
local newtable = mytable * secondtable
show(newtable)
end
main()