Why does pairs reorder my dictionary of str: udim2?

local FinalPositions = {
    ["Youtube"] = UDim2.new(0.26, 0, 1.11, 0);
    ["Cash"] = UDim2.new(0.265, 0, 1.858, 0);
    ["Gold"] = UDim2.new(0.265, 0, 2.617, 0);
}
for tab, finalPosition in pairs(FinalPositions) do
    print(tab)
end
--[[
  01:11:04.129  Gold  -  Studio
  01:11:04.129  Youtube  -  Studio
  01:11:04.129  Cash  -  Studio
--]]

Why does the order change? I can work around this issue but I’m mainly curious.
Thanks in advance.

Arrays are ordered.
Dictionaries are not.

I’m bad at explanations and the sentence I wrote ended up as just gibberish, so I’m afraid I can’t provide anything further, other than what was stated above.

What use case are you having the dictionary for?
You may be able to have an array, containing “Youtube”, “Cash”, “Gold” etc. (without the UDim2 stuff), which I’ll call A. You can then loop through A (using for index, item in ipairs(A) do), and print out the value of it in the dictionary, FinalPositions (i.e. FinalPositions[item])

3 Likes

PoppyandNeivaarecute’s post is your answer, though if you’re curious:

If you want them ordered you’ll need to use an array such as:

local FinalPositions = {
    {Name = "Youtube", Dim = UDim2.new(0.26, 0, 1.11, 0)};
    {Name = "Cash", Dim = UDim2.new(0.265, 0, 1.858, 0)};
    {Name = "Gold", Dim = UDim2.new(0.265, 0, 2.617, 0)};
}

Then use ipairs instead of pairs:

for index, dataDict in ipairs(FinalPositions) do
    print(index) -- Will be ordered
end

ipairs goes over the array part of the table in order.

The dictionary part of the table doesn’t have a guaranteed order, so pairs (which goes over both parts of the table) doesn’t have a guaranteed order either.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.