API sort

From Warcraft Wiki
Jump to navigation Jump to search

Sort the array portion of a table in-place (i.e. alter the table).

table.sort(table [, compFunc])
sort(table[, compFunc])

Arguments

table
Table - Table the array portion of which you wish to sort.
compFunc
Optional Function - Comparison operator function; the function is passed two arguments (a, b) from the table, and should return a boolean value indicating whether a should appear before b in the sorted array. If omitted, the following comparison function is used:
function (a, b)
 return a < b
end

Example

> t = { 3,2,5,1,4 }
> table.sort(t)
> = table.concat(t, ", ")  -- display sorted values
1, 2, 3, 4, 5

A comparison function can be provided to customise the element sorting. For instance, to sort the elements in descending order:

> function isGreaterThan(a, b) return a > b end
> table.sort(t, isGreaterThan)
> = table.concat(t, ", ")
5, 4, 3, 2, 1

Details

  • Only the array portion of the table -- integer indices from 1 to #table -- will be affected by this function.
  • The default comparison function will only work propertly if all values stored in the table are numbers, or if all values stored in the table are strings.
  • The iteration order over key/value pairs in a hash table (using pairs) is undefined. If you need to iterate over hash table elements in a specific order, you'll have to extract the keys to a separate table, and sort that. See orderedpairs for an example.

See also