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.sumin the standard library.It’d be more useful to implement
table.reducealong the lines of:And use it with a simple lambda:
The example implementation of
reducelacks type-checking but you should get the idea.