How to put the same code to different metamethods in Lua?

Viewed 41

The code below works but I have the same code in 2 metamethods. Is is possible to make __add and __sub have the same code without repeating it?

local function doMath(tbl, num, op)
  local sum = 0
  for _, v in next, tbl do
    sum = sum + tonumber(v) or 0
  end
  return op == 'add' and sum + num or sum - num
end

local mt = {
  __add = function(t, n)
    return doMath(t, n, debug.getinfo(1, 'n').name)
  end,

  __sub = function(t, n)
    return doMath(t, n, debug.getinfo(1, 'n').name)
  end
}

print(setmetatable({1, 2, 3}, mt) + 5)
1 Answers
local someFunc = function (a, b) end

local mt = { __add = someFunc, __sub = someFunc}
Related