If the table contains a key with a specific value

This may be a bit confusing, but I have a table called for example Ant.

This table contains many other (nameless) tables. These tables represent ants and store values.

An example of this:

Ant = {
  {age=3,speed=10},
  {age=6,speed=7}
}

My question is: how would I check if any of the unnamed table inside the Ant table contains a specific value age.

So, for example, I would like to check if any of my ants are 3 years old.

Hope I was clear enough, and thanks in advance!

+3
source share
2 answers

You can go through the table and check:

for i, v in ipairs(Ant) do
  if v.age == 3 then
    print( i )
  end
end

, 3- .

+4

age , - :

function age_iter(t)
    local i = 0
    return function() 
               i = i + 1 
               return t[i] and t[i].age 
           end
end

age:

for age in age_iter(Ant) do
  print(age)
end

, , age 3.

+2

All Articles