Thread: Table Iteration
View Single Post
03-30-13, 03:20 AM   #2
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
The order in which key/value pairs are returned by pairs is undefined, so, basically random. next works the same way. The only way to directly walk through a table in a specific order is to use ipairs.

There are some workarounds, but they all involve creating an extra table with only the keys from the original table as indexed values, sorting it somehow, and then using ipairs on the extra table and value lookups on the original table, eg:

Code:
local t = {
    ["cow"] = "moo",
    ["pig"] = "oink",
    ["other"] = "?",
}

local order = { "cow", "pig", "other" }

for i, k in ipairs(order) do
    local v = t[k]
    -- do something with v
end
The other option would be to switch your table to an indexed table with subtables:

Code:
local t = {
    { "cow", "moo" },
    { "pig", "oink" },
    { "other", "?" },
}
Then you can sort it however you like, and use ipairs on it. However, you can't do direct value lookups anymore.

Without knowing what you're actually doing, it's hard to say what the best method will be.
__________________
Retired author of too many addons.
Message me if you're interested in taking over one of my addons.
Don’t message me about addon bugs or programming questions.
  Reply With Quote