Garry's Mod Wiki

table.sort

  table.sort( table tbl, function sorter = nil )

Description

Sorts a sequential table either ascending or by the given sort function.

This function modifies the table you give to it and internally uses the quick sort algorithm.

Arguments

1 table tbl
The table to sort.
2 function sorter = nil
If specified, the sorting function.
Function argument(s):
1 any a - Item A to test.
2 any b - Item B to test.
Function return value(s):
1 boolean result - Result of the comparison. Return true in this function if you want the first parameter to come first in the sorted array.

Example

Sorting table by an integer

local tbl = { { "Jeff", 8 }, { "Peter", 17 }, { "Shay", 11 }, { "Janine", 1 } } table.sort( tbl, function(a, b) return a[2] > b[2] end )
Output: Table going from highest number to lowest (1: Peter, 2: Shay, 3: Jeff, 4: Janine)

Example

Sorting a player table by a NWInt

local plys = player.GetAll() table.sort( plys, function(a, b) return a:GetNWInt("Score") > b:GetNWInt("Score") end )
Output: Player table sorted by score going from highest to lowest

Example

Sort the table by string keys. We cannot sort non-numeric keys in ages, because they are contained in a hash part whose order is undefined.

local ages = { [ "Jeff" ] = 8, [ "Peter" ] = 17, [ "Shay" ] = 11, [ "Janine" ] = 1, } local names = table.GetKeys( ages ) table.sort( names ) for _, name in ipairs( names ) do print( name, ages[ name ] ) end
Output: Janine 1 Jeff 8 Peter 17 Shay 11