Table.sort() / unexpected output

Hello,

I’m sorry but I can’t get it work even after 2 hours. What’s wrong with my script?

local players = {}

for i = 1,5,1 do
	players["Player "..i] = math.random(1,100)
end

table.sort(players, 
	function(a,b)
		return a > b
	end
)

for key, value in pairs(players) do
	print(key.." | "..value)
end

Output:

Player 3 | 31
Player 5 | 32
Player 1 | 84
Player 2 | 81
Player 4 | 64

Disired output:

Player 1 | 84
Player 2 | 81
Player 4 | 64
Player 5 | 32
Player 3 | 31

Thank you

1 Like

table.sort only works with arrays, so what you can do is append "Player" after sorting instead of using it in the key:

local players = {}

for i = 1,5,1 do
	players[i] = math.random(1,100)
end

table.sort(players, 
	function(a,b)
		return a > b
	end
)

for key, value in ipairs(players) do
	print("Player "..key.." | "..value)
end
1 Like

You may notice that you can run this script any number of times and the result will always be different. You can’t sort a table in lua that’s not an array because the (non-numeric, unsorted) keys aren’t stored in any order in the first place.

A possible workaround (if you want to avoid altering the original table format) is to create an array that describes the values in your table and sort that instead.

local players = {}

for i = 1,5,1 do
	players["Player "..i] = math.random(1,100)
end

local sortedValues = {}
for _, v in pairs(players) do
  table.insert(sortedValues, v)
end

table.sort(sortedValues, 
	function(a,b)
		return a > b
	end
)

for i, value in ipairs(sortedValues) do
  for j, v in pairs(players) do
    if v==value then i=j end
  end
	print(i.." | "..value)
end
1 Like