Question

It might be a bit confusing, but I have a table, for example, called Ant.

This table, contains a bunch of other (unnamed) tables. These tables represent ants, and hold values.

Kind of like this:

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

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

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

I hope I was clear enough, and thanks in advance!

Was it helpful?

Solution

You can loop through the table and check:

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

It'll print the index at which your 3 year old ants are stored.

OTHER TIPS

If all you need to check the value of age in each sub-table, building a custom iterator is another way:

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

To iterate over all the age value would be:

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

It's easy to modify it to check if one of the age value is equal to 3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top