Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a table of numbers in Lua?

Tags:

sum

built-in

lua

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?

like image 706
voithos Avatar asked Jan 01 '12 20:01

voithos


1 Answers

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.

like image 83
katspaugh Avatar answered Oct 17 '22 09:10

katspaugh