Hello, I’ve been inactive for awhile but recently I’ve been trying to sort a custom leaderboard in LUA.
So first, I tried using table.sort() on a table similar to this.
local members = {PlayerOne = "1000, codyorr4, 50"}
table.sort(members)
local parsedStr = string.split(members.PlayerOne, ",")
local level = parsedStr[1]
local name = parsedStr[2]
local totalXP = parsedStr[3]
now this seemed to work at first, but I noticed that if other users had certain characters in their name then it would mess up the placement order on my leaderboard.
am I using table.sort() incorrectly? and if so which algorithm should I look into for this type of sorting?
yeah, well for my leaderboard im trying to see who has the highest totalXP and list them from greatest to least, my current method worked at first but certain usernames would interfere with the sort function.
I tried using a dictionary, but after I sorted the totalXP values (using an array as the middleman) I couldn’t accurately match the totalXP back up with the usernames, so I tried sorting a string. (and then parsing that after sorting) which failed.
and I don’t want to make the leaderboard manually, i’d prefer if it iterated through all users comparing their totalXP automatically.
I guess to simplify my question I could ask
“How do I sort a table of players from greatest to least based on their TotalXP value”
you would need to get each player and their XP value, and then sort each value associated with each player’s name
players = {
["noob123"] = 4;
["newplayer12"] = 10;
["coyrdo4"] = 0;
}
local names = {} -- to contain all keys
for k, _ in pairs(players) do
table.insert(names,k)
end
table.sort(names-- ,
--[[function(first, second)
return players[first] < players[second] -- sort, least to greatest
--end ]]
)
for k, v in pairs(players) do
print(k.." = "..v)
end
--> should print coyrdo4, noob123, newplayer12 in that order
-- with each value associated
nice, I never thought about comparing the number values inside of the sort function using the dictionary (not the middle man array) as the parent, thank you.