Arithmetic metamethods

The arithmetic metamethods define how an object will behave when used within an arithmetic operation. The arithmetic metamethods are listed here:

  • __add is called for the + operator
  • __sub is called for the - operator
  • __mul is called for the * operator
  • __div is called for the / operator
  • __pow is called for the ^ operator
  • __mod is called for the % operator
  • __unm is called for negation (for example y = -x)

Example

mt={}
mt["__add"] = function(a,b)
    if type(b) == "string" then
        a[#a+1] = b
    elseif getmetatable(a) == getmetatable(b) then
        for k,v in pairs(b) do
            a[#a+1] = v
        end
    else
        error("Invalid datatype for + operator!",0)
    end
    return a
end

t={}
setmetatable(t,mt);

-- Now use + to call the __add metamethod of the table t
t1 = t + "foo"                  --> t[1] = "foo"
t1 = t + "bar"                  --> t[2] = "bar"