2

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

2
  • 2
    do the real keys actually match the same formatting somename#? Commented Mar 10, 2021 at 15:01
  • yeah, "slot" then the number afterwards Commented Mar 10, 2021 at 15:02

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

Create a new table:

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.