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:
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
)
The example implementation of reduce
lacks type-checking but you should get the idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With