如何在Lua中对数字表求和? [英] How to sum a table of numbers in Lua?
问题描述
Lua有内置的sum()
功能吗?我似乎找不到一个,而且我在文档中几乎遍历了所有地方.也许table.sum()
或类似的东西可以遵循当前的惯例.但是由于找不到,所以我不得不实现它:
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?
推荐答案
我不同意,在标准库中具有原始且特定于table.sum
的内容将是多余的.
I disagree, it would be redundant to have something that primitive and specific as table.sum
in the standard library.
按照以下方式实现table.reduce
会更有用:
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
并使用一个简单的lambda来使用它:
And use it with a simple lambda:
table.reduce(
{1, 2, 3},
function (a, b)
return a + b
end
)
reduce
的示例实现缺少类型检查,但您应该了解一下.
The example implementation of reduce
lacks type-checking but you should get the idea.
这篇关于如何在Lua中对数字表求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!