sorting a table

Posted by Renny on Sat 25 Apr 2015 07:42 AM — 5 posts, 18,696 views.

Canada #0
I want to sort a table based on two comparison operations.


t = { 
[1] = { fruit = pear, color = red, rank = 0 }, 
[2] = { fruit = apple, color = orange, rank = 1 }, 
[3] = { fruit = orange, color = green, rank = 2 }, 
[4] = { fruit = potatoe, color = black, rank = 1 },
}


I want to first sort the table by rank numerically, and then sort it by color alphabetically.

So the order would be,


1 = orange, green, 2
2 = potatoe, black, 1
3 = apple, orange, 1
4 = pear, red, 0


I am aware of this function,



table.sort(t, function(a, b) return a.rank > b.rank end)



but don't know how to do a more complicated sort.
USA Global Moderator #1
Maybe
table.sort(t, function(a, b) if a.rank == b.rank then return a.color > b.color else return a.rank > b.rank end)
Canada #2
Fiendish said:

Maybe
table.sort(t, function(a, b) if a.rank == b.rank then return a.color > b.color else return a.rank > b.rank end)



gives me a syntax error

unexpected symbol near ')'
USA Global Moderator #3
Fixing the syntax error left as a learning exercise for the reader. :) If you uncombine the comparison function from the sort invocation, as in

function mysort(a,b)
...

table.sort(t, mysort)

The fix should become obvious.

Also in your table you need to put the colors and fruits in quotation marks, brcause they are strings.

Also potato doesn't end with an e and isn't a fruit.
Amended on Sat 25 Apr 2015 06:19 PM by Fiendish
Canada #4
Fiendish said:

Also potato doesn't end with an e and isn't a fruit.


Thx this works perfect