So I have a remote function which returns the leaderboard data of the round playing, this is not the global leaderboard this is an important distinction because I’m not interested in making an ordered datastore.
The remote function returns an array, normally indexed with a dictionary in the following format.
What I want to do is order the outer array so that the indexed dictionary with the highest kills, and if there is a tie with highest kills then select the one with the lowest deaths, to be placed first in the ordering.
Seems very simple. I’m having a hard time wrapping my head around a more simple solution. I was thinking of using table.Sort, but that’s not really a viable method due to the fact it can’t sort dictionaries and the fact I need to sort depending on two values of the dictionary.
I’m not sure how I would start to script this.
Edit: ok I have one function which will compare two dictionaries and pick the better one of the two.
function betterPlacement(p1,p2)
if p1["kill"] > p2["kill"] then
return p1
elseif p1["kill"] < p2["kill"] then
return p2
else
if p1["death"] <= p2["death"] then
return p1
elseif p1["death"] > p2["death"] then
return p2
end
end
end
Hope this function helps
edit: Oh wait I’m dumb I didn’t realize table.sort had a second argument
I’m confused. You don’t have any table values in your dictionary; you have string keys and string or int values, so it’s a dictionary you’re trying to sort, which you can’t in this case. You can however, make a string key point to a table value, and then sort the table directly:
local dictionary = {
["Stones"] = {1, 2, 3}; --//Sort the table here
}
You are misunderstanding me. I have an array which each index has a dictionary. I am still trying to sort an array, what I am not trying to do is sort a dictionary.
If I understood the question correctly, something like this?
-- convert the dictionary into an array, which would then contain dictionaries (which would be every player's stats individually)
-- get every player's data in this table
local statsForAllPlayers = { -- contains sample data (not sorted)
{name = "player1", kills = 0, deaths = 99, team = "team1"},
{name = "player2", kills = 9, deaths = 1, team = "team2"},
{name = "player3", kills = 3, deaths = 20, team = "team3"},
}
table.sort(statsForAllPlayers, function (a, b)
return a.kills < b.kills
end
)
for _, stat in ipairs(statsForAllPlayers) do
print(stat.name, " = ", stat.kills)
end
-- prints every player's name and kills, with the ascending order of kills
Edit: just flip the operator in the predicate function to > for descending order.