Table.sort errors when other players are in the game

Hi, i am currently working on this game where i would need to sort a table from highest, to lowest. Now, this works in singleplayer, but errors whenever there’s more than 1 player in the game. How would i go on to fix this? Here’s the code

function SendData()
    
    local ClientBoard = {}
    
    for i, v in pairs(GameModule.Settings.Leaderboard) do
        table.insert(ClientBoard, {DisplayName = i.DisplayName, UserID = i.UserId, Points = v.Points})
    end
    

    
    table.sort(ClientBoard, function(a,b)
        return a[2] > b[2]
    end)
    
    Remotes.UI:FireAllClients("RefreshBoard", ClientBoard)
end

In the for i, loop, the i value is the player, and v is the table values in the leaderboard table.

hi, you’re attempting to access properties of the i and v variables within the loop. the i variable is the key in the GameModule.Settings.Leaderboard table, which you’re expecting to be a player object, but it’s not clear from the code what the actual keys of the Leaderboard table are.

similarly, v is the value associated with that key, which you’re expecting to be a table with a Points property. Additionally, in the table.sort function, you’re trying to sort based on a[2] and b[2] , but your tables a and b are dictionaries with named keys, not indexed arrays.

so you should be sorting based on a.Points and b.Points . i tried to fix your code:

function SendData()
    local ClientBoard = {}

    for userId, playerData in pairs(GameModule.Settings.Leaderboard) do
        table.insert(ClientBoard, {
            DisplayName = playerData.DisplayName,
            UserID = userId,
            Points = playerData.Points
        })
    end

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

    Remotes.UI:FireAllClients("RefreshBoard", ClientBoard)
end

:smile:

1 Like

Thank you so much! This worked. This was my first time using this function, so it was really confusing for me, but your explanation helped me understand this more.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.