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?
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.
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)