Table keys not sorting correctly

Viewed 54

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

3 Answers

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

Create a new table:

slot = {}
for k,v in pairs(original_table) do
  local i=tonumber(k:match("%d+$"))
  slot[i]=v
end

Lua table orders are undeterministic. see here what makes lua tables key order be undeterministic

For your table you can try this

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

local slotNumber = 1
while(t['slot' .. slotNumber]) do
   slot = t['slot' .. slotNumber]
   -- do stuff with slot

   slotNumber = slotNumber + 1
end

This method does not handle if the table skips a slot number.

Related