Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How would I loop through a dictionary in order?

Asked by 8 years ago

I've never really required this before, but how would I loop through a dictionary similar to the following:

local Dictionary = {
    ['Thing'] = true;
    ['Thing2'] = false;
    ['SomeOtherThing'] = "Hi";
};

...in order?

The Next and Pairs iterators wouldn't work due to them not looping in order, and the ipairs iterator wouldn't work as the indexes are not numerical. This loop needs to be run without prior knowledge of the structure of this dictionary, so I cannot have a pre-set table of indexes which it reads off and compares with the dictionary.

I also require the index and value of each as variables which I can use within the loop.

Any ideas?

1
What order do you want to them to read in? Alphabetical? In the order they were added? BlackJPI 2658 — 8y
0
Order they were added. darkelementallord 686 — 8y

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago
Edited 7 years ago

Dictionaries do not have an order. This is important to the idea of what a dictionary is, and also important for them being very fast.

The internal order changes as you add and remove elements, and it's not preserved when you write the dictionary as a literal.


You have to store them in a datastructure that has an order.

See this question.

The simplest clean way is to use a list-of-dictionaries:

local things = {
    {key = "Thing", value = true},
    {key = "Thing2", value = false},
}
-- things[1].key is first key; things[1].value is first value;
-- things[2].key is first key; things[2].value is second value;

You could of course just use {"Thing", true}:

local things = {
    {"Thing", true},
    {"Thing2", false},
}
-- things[1][1] is first key; things[1][2] is first value;
-- things[2][2] is first key; things[2][2] is second value;

-- This can be made less ugly than it seems with `unpack`:
for id, pair in ipairs(things) do
    local key, value = unpack(pair)
    ......
end

This is the reason why Perl has => as a synonym for ,. In that style, you would write:

-- (psuedo perl/lua, not lua)
local things = {
    "Thing" => true,
    "Thing2" => false,
}

but what that really means is

local things = {
    "Thing", true,
    "Thing2", false,
}

-- things[1] is first key; things[2] is first value;
-- things[3] is second key; things[3] is second value;

(which is another option for storing your data, but it's much more ugly to deal with)

0
That's a shame that I can't do it my way, but thanks for the prompt response. darkelementallord 686 — 8y
Ad

Answer this question