Table.sort is not sorting the table?

print("BEFORE", Scores)
	-- Sort the PlayerScores into order
	table.sort(Scores, function(a, b)	
		return a.Points > b.Points
	end)
	print("AFTER", Scores)

Both before and after print the same results.

Tables look like so

PlayerScores[player.UserId] = {
		["Tags"] = 0,
		["Deaths"] = 0,
		["Points"] = 0,
		["Streak"] = 0
	}

table.sort doesn’t return your table, it sorts the table that is given.

Instead, do:

print("BEFORE", Scores)
	-- Sort the PlayerScores into order

local sortedtable = table.sort(Scores, function(a, b)	
		return a.Points > b.Points
	end)

print("AFTER", sortedtable)

It looks like “Scores” is a dictionary (with the keys being each player’s UserId). Dictionaries are unordered collections, table.sort only works on arrays.

2 Likes

What’s my best option for storing player scores then?

I don’t want to store each individual score as its own table, id ideally want everything kept cleanly under 1 table

It depends on what you’re doing. Some options you have are:

  • Restructuring the table format so that it is an array
  • Writing a function that can return a sorted set of keys from the dictionary

Here are two examples demonstrating these options (but they are not the only ways):

Changing “Scores” dictionary to array:

local Scores = {}
Scores[50134] = {Points = 10}
Scores[13042] = {Points = 0}

local Scores = {}
table.insert(Scores, {UserId = 50134, Points = 10})
table.insert(Scores, {UserId = 13042, Points = 0})

Using a helper function:

function GetKeySet(dictionary)
  local array = {}
    
  for key in pairs(dictionary) do
    table.insert(array, key)
  end
  
  return array
end

local ScoresKeySet = GetKeySet(Scores)

table.sort(ScoresKeySet, function(aKey, bKey)
  local a = Scores[aKey]
  local b = Scores[bKey]
      
  return a.Points > b.Points
end)

for i, key in ipairs(ScoresKeySet) do
  print(i, Scores[key])
end
1 Like