2
votes

The below table and for loop is how we generally access all the key, value pairs in 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

If I want to iterate only on a subset of this table where loop only iterates on certain keys as shown here

k = a1,a2 

Since I am intending to add more tables in t as

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}
          }

What I want to use something like

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

Is there a way to do this other than adding an if condition within a loop, Since this will iterate through all k,v pairs & not desired

for k,v in pairs (t) do
    if (k == a1 or k == a2) then
    -- something
1
I am aware that for 2 dimensional table, I need another loop but that is not a concern here - wsha

1 Answers

4
votes

you can do it this way

   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

you can see it here

https://repl.it/repls/CoralIndianredVaporware