Check if a value corresponds to a value in an array

Asked

Viewed 155 times

3

How to check if a given value corresponds to another present in an array? Ex:

array1 ={nome = "Fulano", idade = 15}
print(array1[idade].nome)
  • 1

    Can you explain better what you want to check? and give an example of what you mean by array inside array.

  • I think I expressed myself wrong, but that’s what the example says. The array has 2 fields, and I want to check one field of the array for the other, if you use the name of the array, or almost that.

  • Ok, you can edit the question on the "edit" button below.

  • should use quotes here: print(array1[idade], that is to say print(array1["idade"] but then I don’t understand what you want to do with .nome. Want to check whether array1["idade"] is a property object nome?

  • I want to take the value "name" of the array of those who have "age" equal to 15.

1 answer

3


One way to solve this, is to search in all the equivalent age and only use the names that match with age!

Ex:

array1 = {
    {nome = "Paulo", idade = 13},
    {nome = "Fernando", idade = 27},
    {nome = "Fulano", idade = 15},
    {nome = "Rebeca", idade = 15}
}

for i,k in ipairs(array1) do
    if k.idade == 15 then
        print (k.nome) --Ou o que você quiser fazer com o nome
    end
end

The result of this code will print Fulano and Rebeca (Who are 15 years old).

  • Gammeth, perfect, thank you.

  • @Gabrielsales Avoid using the comments to thank, if a reply is useful, check the accepted button (The gray V near the answer) to make it green.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.