Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How would I sort a table numerically while keeping a string value attached to it?

Asked by
SuperFryX 130
8 years ago

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

2 answers

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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.

Ad
Log in to vote
0
Answered by
wazap 100
8 years ago

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

0
Why wouldn't you just use `table.sort` and save 8 lines of code? BlueTaslem 18071 — 8y

Answer this question