Hi, I am trying to create a script that loops through all players in the game, check their cash value and adds both their player name and cash value in a table, so I can loop through the table and get the player name that has the most amount of cash in descending order. How do I do this?
local t = {}
while true do wait()
for _, plr in pairs(game.Players:GetPlayers()) do
local plrName = plr.Name
--This is just to make clear what I mean
t[plr.Name] = 50
t["BOB"] = 23
t["Shedletsky"] = 20
t["DavidBazooka"] = 160
end
print(t)
end

Give this a shot I’m typing on phone so i can’t really test.
function sortZ2A(tbl)
table.sort(tbl, function(a, b) return a[2] > b[2] end)
for k,v in ipairs(tbl) do
print(v[1], ' == ', v[2])
end
end
that looks REALLY complicated, isn’t there an easier way?
Does it not work? If so i can try find another way.
EDIT: Since these are built-functions it runs faster and keeps your code neat, I recommend making something a little bit complicated if it means you minimize performance loss and cognitive overflow
Call this function whenever you want to get a table with the values. Now here is how it will return, a table with tables inside. There will be a table for every single player, and the first key in that table will be their cash, and the second key will be their name. I am assuming the currency is “Cash” with the C capitalized, if it isn’t then just change the part where I reference the cash. I tested this on my end and it worked.
local function SortPlayerCash()
local Array = {}
local PlayersTab = {}
local MainTable = {}
for i, v in pairs(game.Players:GetPlayers()) do
table.insert(Array, v.leaderstats.Cash.Value)
PlayersTab[v.leaderstats.Cash.Value] = v.Name
end
table.sort(Array, function(a, b)
return a > b
end)
for i, v in ipairs(Array) do
table.insert(MainTable, {v, PlayersTab[v]})
end
return MainTable
end
For example, here is an example table:
local rankedPlayers = SortPlayerCash()
print(rankedPlayers) -- Say Bob, Jill and Bill were in the game, it would sort their cash and print the following table
{
{100, "Bob"},
{87, "Jill"},
{22,"Bill"}
}
print(rankedPlayers[1][2]) --prints the name of the richest player
print(rankedPlayers[1][1]) --prints the cash of the richest player
print(rankedPlayers[3][2]) --prints the name of the third richest player
print(rankedPlayers[#rankedPlayers][2])--prints the name of the poorest player