Reputation: 632
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!
Upvotes: 3
Views: 1309
Reputation: 122363
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
.
Upvotes: 2
Reputation: 80629
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.
Upvotes: 4