Search code examples
sortinglua

Table keys not sorting correctly


I have a table that looks like this

{
   ["slot1"] = {}
   ["slot2"] = {}
   ["slot3"] = {}
   ["slot4"] = {}
   ["slot5"] = {}
   ["slot6"] = {}
}

When I do a for k, v in pairs loop I want the keys to go from slot1- the last slot. At the moment when I do a loop the order is inconsistent, slot 5 comes first etc. What is the best way to do this?

also I did not design this table, and I cannot change how the keys look


Solution

  • You can write a simple custom iterator:

    local tbl = {
       ["slot1"] = {},
       ["slot2"] = {},
       ["slot3"] = {},
       ["slot4"] = {},
       ["slot5"] = {},
       ["slot6"] = {}
    }
    
    function slots(tbl)
        local i = 0
        return function()
            i = i + 1
            if tbl["slot" .. i] ~= nil then
                return i, tbl["slot" .. i]
            end
        end
    end
    
    for i, element in slots(tbl) do
        print(i, element)
    end
    
    

    Output:

    1   table: 0xd575f0
    2   table: 0xd57720
    3   table: 0xd57760
    4   table: 0xd5aa40
    5   table: 0xd5aa80
    6   table: 0xd5aac0