How do i use table.sort in player's specific leaderstats value?

Simple: know how do i use table.sort with players and sort a specific value (for example: coins, xp, kills, etc.)

But i don’t know how can i do it. Since i’m new at tables and i have never used table.sort. Since i find it hard to use. I hope you help me :+1: Thanks.

Alright so, you’ll need to iterate through GetPlayers of Players service and add each player’s stat value to an array.

Then using table.sort you can sort it, no need to give a sorting function - the default function will order them acoordingly for you.

Putting that into practice:

--// Dependencies
local Players = game:GetService("Players")
--// Variables
local Array = {}

for _, player in ipairs(Players:GetPlayers()) do
     table.insert(Array, player.Coins.Value)
end

table.sort(Array) 
--// Now do what you'd like

If you’d like to maybe insert a dictionary into the array then you’ll be required to provide your own sorting function.
The sorting function must return a boolean if the second parameter is bigger than the other.

Now, that’d look like:

for _, player in ipairs(Players:GetPlayers()) do
    table.insert(Array, {
        Coins = player.Coins.Value
        Player = player
    })
end

table.sort(Array, function(a, b)
    return a.Coins < b.Coins
end)

table.sort basically sorts a table in the order of the first entry / element to the last entry based on a function where it should return true if the first entry / element should come before the second. Here’s an example:

local tbl = {59, 42, 1, 4, 68, 32}

-- this sorts the table in the order of lowest to highest
-- alternatively, you can just leave the comp function blank because lua automatically sorts it from lowest to highest, but I did it just to show how to use the function
table.sort(tbl, function(a, b)
    return a < b
end)

In your case, you can get all of the player’s coin’s values and put them in a table, along with the player’s name for easy referencing:

local TBL = {}

for _,v in pairs(game.Players:GetPlayers()) do
   TBL[#tbl+1] = {v; v.Coins.Value}
end

table.sort(TBL)
print(unpack(TBL))
2 Likes

And how do i know when a player have more money than other 2 players? Also, this code:

return a.Coins < b.Coins

will only get two players?

  1. They’ll be higher than the other players in the array.

  2. table.sort iterates through the entire table, matching two elements at a time to find where each shall be sorted.

The array, if i use print to print the sorted table, does the print will print the highest value or will print the entire table sorted?

If you directly print an array it’ll print:

table: [hexadecimal memory address]

You’ll need to unpack() it, and it’ll print the table sorted.

1 Like

do the values of the coins update if you change the value of the coin?