I am making a highscore board that will display your ranking. The current code creates a table of all the scores(which are stored in a group filled with int values, the value being the score, and the name of the value being the already defined player name) , and then sorts the scores from greatest to least. However, I also need the name of the player to go along with the scores.
Basically, how would I sort the table while keeping the names defined so I can put it next to their score? The actual player name is stored in v.Name (Which I put a comment in there for) I just need to figure out how to take that name and display it with the rest of them.
local values = {} for _, v in pairs(PlayerNames:GetChildren()) do --v.Name is where the string is stored! table.insert(values, v.Value) end table.sort(values, function(a, b)--Sort the numbers return (a > b) end) place=0 for index, value in ipairs(values) do--Creates a new frame that contains the player score place=place+1 local FrameC=HighscoreScr.Frame1:clone() FrameC.Parent=HSFrame --FrameC.ImageLabel.PlayerText=PLAYERNAME I NEED TO FIND! FrameC.Damage.Text=value FrameC.Visible=true FrameC.Place.Text=place end print("Number of Scores: "..(#values)) HSFrame.Visible=true
table.sort
can compare arbitrary things with the comparator function. You simply want to be comparing based on .Value
:
local values = PlayerNames:GetChildren() table.sort(values, function(a, b) return a.Value > b.Value end)
You now have values
the list of NumberValues, in descending order of their .Value
.
You can get their scores as simply value.Value
and their names as value.Name
.
I would approach this problem differently I would completely ignore the use of table.sort and do something like
local values = {} for _, v in pairs(PlayerNames:GetChildren()) do local index = #values+1 for i = 1, #values do if v.Value < values[i].Value then index = i break; end end table.insert(values, index, {Name=v.Name, Value=v.Value}) end --[[Now to access the value, do for i, v in ipairs(values) v.Name is the name v.Value is the value/score ]]
I'll just assume PlayerNames:GetChildren() is small (around 15 max), because this method of sorting is quite inefficient