Sorting a Lua table by key

Prakash.DTI picture Prakash.DTI · Oct 2, 2014 · Viewed 13.9k times · Source

I have gone through many questions and Google results but couldn't find the solution.

I am trying to sort a table using table.sort function in Lua but I can't figure out how to use it.

I have a table that has keys as random numeric values. I want to sort them in ascending order. I have gone through the Lua wiki page also but table.sort only works with the table values.

t = { [223]="asd", [23]="fgh", [543]="hjk", [7]="qwe" }

I want it like:

t = { [7]="qwe", [23]="fgh", [223]="asd", [543]="hjk" }

Answer

Paul Kulchenko picture Paul Kulchenko · Oct 2, 2014

You cannot set the order in which the elements are retrieved from the hash (which is what your table is) using pairs. You need to get the keys from that table, sort the keys as its own table, and then use those sorted keys to retrieve the values from your original table:

local t = { [223]="asd", [23]="fgh", [543]="hjk", [7]="qwe" }
local tkeys = {}
-- populate the table that holds the keys
for k in pairs(t) do table.insert(tkeys, k) end
-- sort the keys
table.sort(tkeys)
-- use the keys to retrieve the values in the sorted order
for _, k in ipairs(tkeys) do print(k, t[k]) end

This will print

7   qwe
23  fgh
223 asd
543 hjk

Another option would be to provide your own iterator instead of pairs to iterate the table in the order you need, but the sorting of the keys may be simple enough for your needs.