How to sum a table of numbers in Lua?

隐身守侯 提交于 2019-12-10 13:24:36

问题


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?


回答1:


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) 
    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
)

The example implementation of reduce lacks type-checking but you should get the idea.



来源:https://stackoverflow.com/questions/8695378/how-to-sum-a-table-of-numbers-in-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!