~/Table Sorting in Lua

Jul 14, 2019


Sorting a table in Lua is typically done with the built in table.sort function. By default, table.sort sorts arrays of numbers or strings in ascending order.

Sort a simple array:

1
2
3
local t = {5, 2, 8, 1}
table.sort(t)
-- t is now {1, 2, 5, 8}

Sort a table with custom comparison:

1
2
3
local t = { {score=5}, {score=2}, {score=8} }
table.sort(t, function(a, b) return a.score > b.score end)
-- sorts t by descending score

table.sort cannot sort keys in tables used as dictionaries; it only works on sequential arrays. To sort dictionary keys:

1
2
3
4
5
6
7
local dict = {a = 3, c = 1, b = 2}
local keys = {}
for k in pairs(dict) do table.insert(keys, k) end
table.sort(keys)
for _, k in ipairs(keys) do
  print(k, dict[k])
end

More details on table.sort and table handling can be found in the official Lua documentation.

Tags: [lua] [tables] [sorting]