Order table by contained value

6

I want to sort this table by a value contained in it. Ex:

tabela = {
{pessoa="Joao", idade=20},
{pessoa="Pedro", idade=22},
{pessoa="Lucas", idade=19},
{pessoa="Derp", idade=25}
}

I want to sort the table by age. Something like:

table.sort(tabela, function(table, value1, value2) return table.value1 < table.value2 end)
for x=1, table.maxn(tabela) do
print(tabela[x].idade)
end

Return:

25
22
20
19
    
asked by Gabriel Sales 08.10.2014 в 07:54

1 answer

8

You've come close. But it has three errors.

  • You are receiving the parameters unduly. This lambda that table.sort fault waits receives only two parameters that represent the two items to be compared. These items are independent values, you do not need and can not receive the table. The way you did you're getting the table and picking up her items. So, in theory, you would not even need the subsequent parameters. But it's just the opposite of what you need. This lambda can not have the signature you want because it will be called by table.sort . It needs to conform to the established specification.

  • You are getting the whole item to compare instead of the specific item, ie you need to take the age of the table and not the table that the function receives. I do not know if you noticed you have a nested table. Then its anonymous function passed to table.sort is receiving a table with the items pessoa and idade . So far so good. But you're trying to compare the table and it does not (not to be confused with the main table, it's the inside table, eg {pessoa="Joao", idade=20} ). You need to compare an item in the table. This item is idade .

  • And you showed that you want the descending ordering which would require the comparison to be with a "greater than" sign. You would probably realize this when you resolved the previous problem.

Then it would look something like this:

tabela = {
    {pessoa = "Joao", idade = 20},
    {pessoa = "Pedro", idade = 22},
    {pessoa = "Lucas", idade = 19},
    {pessoa = "Derp", idade = 25}
}
table.sort(tabela, function(value1, value2) return value1.idade > value2.idade end)
for x = 1, table.maxn(tabela) do
    print(tabela[x].idade)
end

See running on ideone . And < strong> Coding Ground . Also I placed GitHub for future reference .

    
08.10.2014 / 08:24