Ordering a table using information from another table

Hello,

I’ve had trouble creating an efficient script to sort table elements.

In my script, I have an array that contains arrays inside it. This is what it would look like:

local data = {
       {plr1,numOfCoins},
       {plr2,numOfCoins},
       --etc

}

local standings = {}

In the code above, what I have is an array that contains more arrays that contain the player as the first index, and the number of coins as the second index. What I am trying to do is put the rankings of the players in the “standings” array, from greatest to least.

So, if Player1 has 15 coins, and player2 has 50, then I want the “standings” array to be like this:

     {player2,Player1}

What code should I make to read off of the “data” table and put in “standings” the players in order from their greatest to least coins.

I am really not sure what an efficient way to do this is, and I would be really grateful if someone gave me some help. I’m fine with pseudocode!

Thank you!

This is actually quite simple, you need to define your comp function for table.sort. The function is internally called repeatedly passing each element and the next one as parameters (a and b). Since your array contains the coin value as the 2nd index, we want to compare that:

local function sortCoins(a, b)
    return a[2] > b[2] --flip the symbol for ascending order
end

table.sort(data, sortCoins) --sortCoins is our comp function

In general, you can sort any type of arrays if you design that comp function to suit your circumstance.

1 Like

This works, but how will the script know which exact player has how many coins? That’s what I was wondering about. Do you have any idea on how we can figure that out?

Thank you for helping!

a/b refers to the table {plrX, numOfCoins}, meaning a[2]/b[2] refers to the second position of that table, aka your numOfCoins.

1 Like

You could assign a hash value for them so you can get the data quickly, what i mean is like put their pointer address in the same log as the sorted array in the player coins

1 Like