Table sorts the way I don't want it to be sorted

How I add to the table:

gamedata[player.UserId] = {
  kills = Kills.Value
}

How I sort the table:
(I’m trying to sort it by most to least kills)

table.sort(gamedata, function(p1, p2) 
  return p1.kills > p2.kills
end)

Output:

--[[
gamedata = {
   ["-1"] = {
      ["kills"] = 0
   },
   ["-2"] = {
      ["kills"] = 1
   }
}
]]

note that player id -1 got a kill, not player id -2.

In accordance to the Lua 5.1 Reference Manual, § 5.5 table.sort:

Sorts table elements in a given order, in-place , from table[1] to table[n] , where n is the length of the table.

So the table.sort functions only sorts from positive indices [1, n], which -1 and -2 aren’t in therefore it will not be sorted.

Rather than setting the indices of the table gamedata to integers outside of an ordinal range. Try putting the user id inside the table containing the index kills and insert that table to the table gamedata.

So instead of

gamedata[player.UserId] = {
  kills = Kills.Value
}

…try

table.insert(gamedata, {
        userid = player.UserId,
        kills = Kills.Value,
}
2 Likes