--找到表中最后一个元素的下标
function tableMax(t)
local count = 0
for k,value in ipairs(t) do
if (count < k) then
count = k
end
end
return count
end
local mt = {}
mt. __add = function(mytable,newtable)
for i = 1,tableMax(newtable) do
--table.insert(table1, pos, table2)
table.insert(mytable,tableMax(mytable)+1,newtable[i])
end
return mytable
end
mt. __sub = function(mytable, newtable)
local tmp = {}
for k, v in ipairs(mytable) do
tmp[k] = newtable[k] - mytable[k]
end
return tmp
end
mt. __mul = function(mytable, newtable)
local tmp = {}
for k, v in ipairs(newtable) do
tmp[k] = newtable[k] * mytable[k]
end
return tmp
end
function showargTable(t)
for key, value in pairs(t) do
print("table["..key.."] = "..value )
end
end
function main()
mytable = {1,2,3}
local secondtable = {20,40,50}
setmetatable(mytable,mt)
local mytable = mytable + secondtable
--local mytable = secondtable - mytable
--showargTable(mytable)
local mytable = mytable * secondtable
showargTable(mytable)
end
上面的代码表示的是操作两个table元素 进行加法、减法以及乘法运算