Does Lua have a builtin sum()
function? I can't seem to find one, and I've looked almost everywhere in the documentation. Maybe table.sum()
, or something of the like, to follow the current conventions. But since I couldn't find it, I had to implement it:
function sum(t)
local sum = 0
for k,v in pairs(t) do
sum = sum + v
end
return sum
end
It seems kind of funny to have to implement something this simple, though. Does a builtin function exist, or no?
I disagree, it would be redundant to have something that primitive and specific as table.sum
in the standard library.
It'd be more useful to implement table.reduce
along the lines of:
---Reduces an array
---@param list any[] An array
---@param fn function The reduction predicate
---@param init any The initial accumulator value
---@return any The final value of the accumulator
table.reduce = function (list, fn, init)
local acc = init
for k, v in ipairs(list) do
if 1 == k and not init then
acc = v
else
acc = fn(acc, v)
end
end
return acc
end
And use it with a simple lambda:
table.reduce(
{1, 2, 3},
function (a, b)
return a + b
end,
0
)
The example implementation of reduce
lacks type-checking but you should get the idea.