user10601169
user10601169

Reputation:

Iterate over table of tables

I have this table local cookies = {{["name"]=23, ["value"]=333}, {["name"]=222, ["value"]=33233}} and I want to iterate over the subtables to find the one with the correct "name". Here is what I have tried

  for _,elm in ipairs(cookies) do
    for k,v in ipairs(elm) do
      print(k)
      if k == "name" and v == 222 then
          print(v)
      end
    end
  end

I does show in the outer for loop that it sees to tables, however, it does not even enter the inner for loop - why? How can I find the subtable for which "name" equals a certain value?

Upvotes: 3

Views: 694

Answers (1)

Curtis Fenner
Curtis Fenner

Reputation: 1403

ipairs only iterates over the keys 1, 2, 3, ..., so it won't visit the key "name". If you want to visit all keys, use pairs (though be warned the order of iteration is not predictable).

However, for your example you don't need an inner loop at all. You can simple get the name of elm as elm.name:

for _,elm in ipairs(cookies) do
    if elm.name == "222" then
        print(elm.name, elm.value)
    end
end    

In fact, if you don't need the ordering or need to support duplicated cookie names, your cookies table could become a dictionary of name => value, allowing you to write this with no loops:

print(cookies["222"]) --> 33233

Upvotes: 4

Related Questions