Getting all the players and selecting 10 with the best "score"?

Im attempting to create a scoreboard. each player has a “score”. and I need to pick out 10 players with a score from largest to smallest.

so far what ive done is create a folder, and I added 10 int values A-J. A has 100 points, and each letter up is 100 more, with J ending at 1000.

The script I made gets all the values, records their score in another table, organizes it, then it will compare the table with everything with the organized scores were it will match the names with what number belongs to them.

It will then insert the result in a third table were the contents will be printed.

this is the code ive made with it so far:

local baselist = game.Workspace.TestFolder:GetChildren()
local fulllist = {
}
local namelist = {}
local scorelist = {}


--form full dictionary of info--
for _, p in pairs(baselist) do
fulllist[p.Name] = p.Value
end
-------------------------------


--get scores from full list--
for k, v in pairs(fulllist) do
table.insert(scorelist,v)
end
-----------------------------



--sort scores--
table.sort(scorelist)
---------------


--transpate scores to their respective owners and out it in a table--
for k, v in pairs(fulllist) do
local fetch = table.find(scorelist,v)
if fetch and namelist[fetch] == nil then
table.insert(namelist,fetch,k)
end
end
print(#namelist)
---------------------------------------------------------------------

the output is:
A B C D E F nil G I J

the problems are:
the result contains nil and some names are not listed properly.
I still need to figure out how to make this work with more or less than 10 in the table with everything.

Im not even quite sure if this is the best approach into the creation of a leaderboard. any help is appreciated.

create a table
loop through each player and set the index to the score and the value to the player
if 2 players have the same score turn the value into another table with both players in it

then go trough that table using ipairs and flipt the table to have 1 as the highest coring player

You could use the table.sort() ability to give it a different compare-function, which then compare against the items’ Value field (or another field the item contains.)

Something like:

local baselist = game.Workspace.TestFolder:GetChildren()
table.sort(
   baselist,
   function(itemA, itemB)
      return itemA.Value > itemB.Value
   end
)
for idx, v in ipairs(baselist) do
   print(idx, " - Name:", v.Name, " Score:", v.Value)
end
1 Like

I didnt know you could use table.sort with dictionaries or use functions right inside. that’s pretty neat.