使用选定的键遍历表

时间:2018-09-18 12:56:44

标签: lua lua-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

如果我只想对该表的子集进行迭代,则循环仅对某些键进行迭代,如此处所示

k = a1,a2 

由于我打算在t中添加更多表,

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

1 个答案:

答案 0 :(得分:3)

您可以这样做

   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