14

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" }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Prakash.DTI
  • 913
  • 2
  • 9
  • 19
  • 1
    What problem are you really trying to solve? – lhf Oct 02 '14 at 12:12
  • Do not confuse a _table constructor_ (which has an ordered list of values with optional keys)—a source code concept—with an _actual table_ —a run-time data structure. The order in the table constructor is only relevant to the assignment of implicit keys. – Tom Blodget Oct 02 '14 at 16:35
  • Back to "What problem are you really trying to solve?" You seem to want to store or use more information/structure than you have in your code. Please explain the goal. It could be that you want an iterator. It could be that you want a different table structure. …. – Tom Blodget Oct 02 '14 at 16:49

4 Answers4

26

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.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
7

What was said by @lhf is true, your lua table holds its contents in whatever order the implementation finds feasible. However, if you want to print (or iterate over it) in a sorted manner, it is possible (so you can compare it element by element). To achieve this, you can do it in the following way

for key, value in orderedPairs(mytable) do
  print(string.format("%s:%s", key, value))
end

Unfortunately, orderedPairs is not provided as a part of lua, you can copy the implementation from here though.

vetham
  • 116
  • 3
2

The Lua sort docs provide a good solution

local function pairsByKeys (t, f)
    local a = {}
    for n in pairs(t) do table.insert(a, n) end
    table.sort(a, f)
    local i = 0      -- iterator variable
    local iter = function ()   -- iterator function
        i = i + 1
        if a[i] == nil then return nil
        else return a[i], t[a[i]]
        end
    end
    return iter
end

Then you traverse the sorted structure

local t = { b=1, a=2, z=55, c=0, qa=53, x=8, d=7 }
for key,value in pairsByKeys(t) do
    print("  " .. tostring(key) .. "=" .. tostring(value))        
end
Paul Hilliar
  • 579
  • 6
  • 8
0

There is no notion of order in Lua tables: they are just sets of key-value pairs.

The two tables below have exactly the same contents because they contain exactly the same pairs:

t = { [223] = "asd" ,[23] = "fgh",[543]="hjk",[7]="qwe"}
t = {[7]="qwe",[23] = "fgh",[223] = "asd" ,[543]="hjk"}
lhf
  • 70,581
  • 9
  • 108
  • 149
  • you are right but can we set keys it to ascending order because when i compare this two table it will out come as different because when i compare the first key value pair that will be t[223] and [7].if the both table are in ascending order then i can easily find the missing keys. – Prakash.DTI Oct 02 '14 at 12:26
  • 3
    The manual [says](http://www.lua.org/manual/5.2/manual.html#pdf-next): "The order in which the indices are enumerated is not specified, even for numeric indices." It may even change from one run of the program to the other. – lhf Oct 02 '14 at 12:37
  • 2
    How is this an answer though? It's just "give up". – feos Feb 21 '19 at 22:18