What do you want to achieve? Keep it simple and clear!
I am trying to make a map voting system that is already done i just need to get the map with the most votes.
What is the issue? Include screenshots / videos if possible!
I am trying to sort a table from the highest value to the lowest using table.sort. But yeah that doesn’t work.
What solutions have you tried so far? Did you look for solutions on the Developer Hub?
Well I’ve found one topic about this and that didn’t fix it.
The code
local validMaps = game.ServerStorage.GameFiles.MapVoteFiles.ValidMaps:GetChildren()
local mapCounts = {
[validMaps[1].Name] = 0,
[validMaps[2].Name] = 0,
[validMaps[3].Name] = 0
}
for _, child in pairs(game.ServerStorage.GameFiles.MapVoteFiles.PlayersVoted:GetChildren()) do
mapCounts[child.Value] += 1
print(mapCounts) -- prints normally isn't sorted
end
table.sort(mapCounts, function(a,b)
return a > b
end)
print(mapCounts) -- this part isn't sorted either.
return mapCounts[1]
This will get and compare the values of each entry of the table named “mapCounts” as opposed to the entire key & value pairs which cannot be compared in the same way.
i tried that before, it doesnt fix the issue. that would work if it was a table inside a table but it isnt. when i print one value from the table it prints the integer not the entire key and value.
table.sort can only be used to sort arrays, not dictionaries, what you could do is convert the table into a table of dictionaries (an array) and then perform the sort, as in the following:
local mapCounts = {
{"map1", 2},
{"map2", 4},
{"map3", 1}
}
function sortTable(a, b)
return a[2] < b[2]
end
table.sort(mapCounts, sortTable)
for i, v in pairs(mapCounts) do
print(v[1], v[2])
end
Okay, that works i just modified it a bit this is the code now
local validMaps = game.ServerStorage.GameFiles.MapVoteFiles.ValidMaps:GetChildren()
local mapCounts = {
{validMaps[1].Name, 0},
{validMaps[2].Name, 0},
{validMaps[3].Name, 0}
}
for _, child in pairs(game.ServerStorage.GameFiles.MapVoteFiles.PlayersVoted:GetChildren()) do
for _, key in pairs(mapCounts) do
if (key[1] == child.Value) then
key[2] += 1
end
end
end
table.sort(mapCounts, function(a,b)
return a[2] > b[2]
end)
return mapCounts[1]