Prakash.DTI
Prakash.DTI

Reputation: 792

Sorting a Lua table by key

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" }

Upvotes: 16

Views: 28864

Answers (4)

Paul Hilliar
Paul Hilliar

Reputation: 738

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

Upvotes: 5

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

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.

Upvotes: 28

vetham
vetham

Reputation: 114

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.

Upvotes: 6

lhf
lhf

Reputation: 72402

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"}

Upvotes: 0

Related Questions