对 LUA 中嵌套的 table 项进行操作

Operating over nested table items in LUA

如何使用 LUA 添加嵌套 table 中的某些值。

假设对于列表中不确定数量的项目,我希望得到将所有“计数”值添加到一个变量中的结果。

在以下只有 2 个项目的示例中,期望的结果是拥有一个值为“5”的变量,因为它添加了“master”和“master”的“count: 3”和 count: 2”值分别为“数据”项。

spec:
  nodeSets:
  - config:
      node.store.allow_mmap: true
    count: 3
    name: master
    podTemplate:
      metadata:
        annotations:
          sidecar.istio.io/inject: "false"
  - config:
      node.store.allow_mmap: true
    count: 2
    name: data
    podTemplate:
      metadata:
        annotations:
          sidecar.istio.io/inject: "false"

要从每个配置访问 count 值,您不一定需要遍历嵌套结构,这将需要多个嵌套 for 循环。 想像这样的结构

letters = {
    a = {1, 2, 3, 4, 5},
    b = {6, 7, 8, 9, 10},
    c = {11, 12, 13, 14, 15},
}

这里我们需要 2 个 for 循环,一个用于检索字母中的项目,一个用于检索这些项目中包含的所有嵌套。

只需 1 个循环即可解决您的问题。我们只需要遍历 table nodeSets 并索引存储在 table.

中的每个值的计数
local sum = 0; 
for _,node in pairs(obj.spec.nodeSets) do
    sum = sum + node.count 
end