How to sum table of numbers in Lua?

Does Lua have a built-in sum() function? I can't seem to find him, and I looked at the documentation almost everywhere. Maybe table.sum() or something similar to follow current conventions. But since I could not 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 funny that you need to implement something so simple. Is there a built-in function or not?

+4
source share
1 answer

I do not agree, it would be superfluous to have something primitive and specific like table.sum in the standard library.

It would be more useful to implement table.reduce by line:

 table.reduce = function (list, fn) local acc for k, v in ipairs(list) do if 1 == k 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 ) 

There is no type checking in the reduce implementation example, but you should get this idea.

+10
source

Source: https://habr.com/ru/post/1388839/


All Articles