I have a voting system where i store each players vote amounts in NumberValues. And i need a way to find which Value is the highest out of the table.
Its my first time using tables so still a bit unsure how to use them, i cant seem to ONLY get the name of the player with most votes.
I have searched around and did alot of troubleshooting, at the end of my script you can try print(KillTable[1]) or 2 but it only returns nil.
local KillTable = {}
local Players = game:GetService("Players")
for i,Player in pairs(Players:GetPlayers()) do
local plrTicker = repStore.VoteValues:FindFirstChild(Player.Name)
table.insert(KillTable, plrTicker.Value, plrTicker.Name)
end
table.sort(KillTable, function(a, b)
if a > b then
return a
end
end)
print(KillTable)
local KillTable = {}
local Players = game:GetService("Players")
for i,Player in pairs(Players:GetPlayers()) do
local plrTicker = repStore.VoteValues:FindFirstChild(Player.Name)
KillTable[plrTicker.Name] = plrTicker.Value
end
table.sort(KillTable, function(a, b)
if a > b then
return a
end
end)
print(KillTable)
Just chipping in here, really awful solution probably but it’ll get you the winner. It’s because the indexes resemble the votes (so if 9 was the lowest, the index would be 9 etc)
local earliestIndexNum = 0
repeat
earliestIndexNum += 1
wait()
until KillTable[earliestIndexNum] ~= nil
local winner = KillTable[earliestIndexNum]
print(winner)
Add this below your sort.
EDIT: Hope you didn’t run this, I may have forgotten to add wait()…
Alright I figured out why your original implementation didn’t work and what you can do to fix it. Your old table.insert implementation meant that you were making the vote count the ‘index/position’ in this case, which is the incorrect way to do it.
The way around it is, make your table.insert something like this, that contains the player name and vote count of that player within it like so:
Then when you do your table.sort, instead of comparing a > b directly, you’ll now need to do a.VoteCount and b.VoteCount in this example, because a and b are basically the objects in the array itself.
table.sort(KillTable, function(a, b)
return a.VoteCount > b.VoteCount
end)
At the bottom, you should now just be able to do:
print("Player with most votes (" .. KillTable[1].VoteCount .. "): " .. KillTable[1].PlayerName .. "!")