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