Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to make Dictionaries stay in order?

So I'm making a game that has a GUI to show your score, but I've noticed that my code, which iterates through the dictionary using pairs(), sometimes doesn't keep the original order; When I make the dictionary, the order is PointsWon, PointsTied, PointsLost, but when I iterate through it, the order is PointsTied, PointsLost, PointsWon.

1 answer

✓ Accepted answer

pairs does not care about order, you have 2 solutions here, first is to use array instead, it hurts readability because you would have to remember the numbers but adds performance:

local Table = {
	[1] = 0,		-- PointsWon
	[2] = 0,		-- PointsTied
	[3] = 999,		-- PointsLost
}

for Index, Value in ipairs(Table) do
	print(Index, Value)
end

-- 1 0
-- 2 0
-- 3 999

ipairs only works for arrays and it goes by order just like for loop. The second option is to create array of orders like this:

local Order = {"PointsWon", "PointsTied", "PointsLost"}

local Table = {
	PointsLost = 34893,
	PointsWon = 0,
	PointsTied = 0,
}

for _, Key in ipairs(Order) do
	local Value = Table[Key]

	print(Key, Value)
end

-- PointsWon 0
-- PointsTied 0
-- PointsLost 34893

This discussion is preserved as it was. New answers, comments, and votes are closed.