Sorting a Lua table by key
Asked Answered
J

4

16

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" }
Jeffers answered 2/10, 2014 at 11:59 Comment(3)
What problem are you really trying to solve?Crofter
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.Clank
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. ….Clank
C
28

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.

Campanula answered 2/10, 2014 at 17:50 Comment(0)
M
6

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.

Markham answered 2/10, 2014 at 13:28 Comment(0)
V
4

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
Vagal answered 24/11, 2021 at 13:21 Comment(0)
C
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"}
Crofter answered 2/10, 2014 at 12:10 Comment(3)
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.Jeffers
The manual says: "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.Crofter
How is this an answer though? It's just "give up".Worrywart

© 2022 - 2024 — McMap. All rights reserved.