使用选定的键遍历 table

Iterate through table using selected keys

下面的table和for循环是我们通常访问lua

中所有键值对的方式
local t = {a1 =11, a2=22, c=3, d=4}

for k, v in pairs(t) do
  print(k,v)
end

-- Output: k = a1, a2, c, d & v = 11, 22, 3, 4 respectively
  a1 11  
  a2 22
  c  3
  d  4

如果我只想迭代此 table 的子集,其中循环仅迭代某些键,如此处所示

k = a1,a2 

因为我打算在 t 中添加更多 table 作为

local t = {
          {a1 = 11, a2 = 22, c = 3, d = 4},
          {a1 = 12, a2 = 23, c = 2, d = 4},
          {a1 = 13, a2 = 24, c = 1, d = 4},
          {a1 = 14, a2 = 25, c = 0, d = 4},
          {a1 = 15, a2 = 26, c = 0, d = 4}
          }

我想用的东西类似

for k = {a1, a2} in pairs (t) do
-- something
end

有没有办法做到这一点除了在循环中添加一个 if 条件,因为这将遍历所有 k,v 对而不是期望的

for k,v in pairs (t) do
    if (k == a1 or k == a2) then
    -- something

你可以这样做

   local t = {
      {a1 = 11, a2 = 22, c = 3, d = 4},
      {a1 = 12, a2 = 23, c = 2, d = 4},
      {a1 = 13, a2 = 24, c = 1, d = 4},
      {a1 = 14, a2 = 25, c = 0, d = 4},
      {a1 = 15, a2 = 26, c = 0, d = 4}
      }
local keys_to_iterate = {"a1", "a2"}

for index = 1, #t do
  for k = 1, #keys_to_iterate do
    if t[index][keys_to_iterate[k]] then
      print(keys_to_iterate[k] , t[index][keys_to_iterate[k]])
    end
  end
end

你可以在这里看到

https://repl.it/repls/CoralIndianredVaporware