So, I'm trying to learn metamethods. I'm trying to make a script that can add arrays of numbers together, but will error if there's non-number elements in either table. Here's what I have:
t1 = {1, 2, 3}
t2 = {4, 5, 6,"swag noob"}
mt = {
__add = function(t1, t2)
for _, v in pairs(t1) do --Check table 1 for non-number values
if not type(v) == "number" then
error("Numbers. You need to use numbers!")
return
end
end
for _, v in pairs(t2) do --Same for table 2
if not type(v) == "number" then
error("Numbers. You need to use numbers!")
return
end
end
local sumtable = {} --Table of sums
local function add(iterations)
for i = 1, iterations do
table.insert(sumtable, t1[i] + t2[i]) --Add elements, put sums in sum table
end
end
if #t1 > #t2 then add(#t2) --The next few lines are to make sure that we're not adding elements that don't exist.
elseif #t1 < #t2 then add(#t1)
else add(#t1) end
return sumtable
end
}
setmetatable(t1, mt)
print(table.concat(t1 + t2, ", "))
Although "swag noob" is not a number value, the output won't error. It will add 1 to 4, 2 to 5, and 3 to 6. That's not what I want. When I take 6 out of the table and leave "swag noob", I get...
Workspace.Script:24: attempt to perform arithmetic on field '?' (a string value)
The errors are supposed to be caught in the beginning of the metamethod, but they aren't.
