WoW:API sort: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
m (Changed < to < because it was messing up the instructions) |
||
Line 20: | Line 20: | ||
> t = { 3,2,5,1,4 } | > t = { 3,2,5,1,4 } | ||
> table.sort(t, function(a,b) return a | > table.sort(t, function(a,b) return a<b end) | ||
> = table.concat(t, ", ") | > = table.concat(t, ", ") | ||
1, 2, 3, 4, 5 | 1, 2, 3, 4, 5 | ||
Line 26: | Line 26: | ||
We can see if we reverse the comparison the sequence order is reversed. | We can see if we reverse the comparison the sequence order is reversed. | ||
> table.sort(t, function(a,b) return a | > table.sort(t, function(a,b) return a>b end) | ||
> = table.concat(t, ", ") | > = table.concat(t, ", ") | ||
5, 4, 3, 2, 1 | 5, 4, 3, 2, 1 |
Revision as of 11:36, 15 March 2005
From TableLibraryTutorial of lua-users.org.
table.sort(table [, comp])
Sort the elements of a table in-place (i.e. alter the table).
> t = { 3,2,5,1,4 } > table.sort(t) > = table.concat(t, ", ") -- display sorted values 1, 2, 3, 4, 5
If the table has a specified size only the range specified is sorted, e.g.,
> t = { 3,2,5,1,4; n=3 } -- construct a table with user size of 3 > table.sort(t) -- sort will be limited by user size > = table.concat(t, ", ") -- only specified size is concatenated as well 2, 3, 5
A comparison function can be provided to customise the element sorting. The comparison function must return a boolean value specifying whether the first argument should be before the second argument in the sequence. The default behaviour is for the < comparison to be made. For example, the following behaves the same as no function being supplied:
> t = { 3,2,5,1,4 } > table.sort(t, function(a,b) return a<b end) > = table.concat(t, ", ") 1, 2, 3, 4, 5
We can see if we reverse the comparison the sequence order is reversed.
> table.sort(t, function(a,b) return a>b end) > = table.concat(t, ", ") 5, 4, 3, 2, 1