在LUA中计算2D数组(表)的总和 [英] Calculating Sum of 2D Array(Table) in LUA
问题描述
我只是想知道如何在lua中计算2D数组或表中的组件之和.我尝试搜索,但似乎没有任何清晰或简单的方法.
I was just wondering how to calculate the sum of the components within a 2D array or table in lua. I've tried searching but there doesn't seem to be any clear or simple way of doing it.
我有一个5x5矩阵,该矩阵具有随机生成的单元格,我想知道在给定时间的这些值的总和.
I have a 5x5 Matrix that have randomly generated cells and i was looking to know the sum of these values at a given time.
lua中是否内置任何东西,例如sum(matrix)或sumof(matrix [] []).
Is there anything built into lua such as sum(matrix) or sumof(matrix[][]).
预先感谢
推荐答案
lua 中内置了任何东西,例如 sum(matrix) 或 sumof(matrix[][]).
there anything built into lua such as sum(matrix) or sumof(matrix[][]).
不.只需遍历元素并添加:
No. Just iterate through the elements and add:
local sum = 0
for ir,row in pairs(matrix) do
for ic,col in pairs(row) do
sum = sum + col
end
end
这篇关于在LUA中计算2D数组(表)的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!