I’m trying to sort a dictionary but I can’t figure out how to do this, it works on a normal table but not a dictionary, I think the problem is that a dictionary has string key’s so it can’t be sorted like a normal table that has numbered keys, but I need to be able to keep the player’s userID or username with their individual number somehow.
Code:
math.randomseed(tick())
local Table1 = {
["Complextic"] = 1;
["Stinger"] = 20;
["Beluga"] = 8;
["Iogician"] = 2;
["LimitedUHax"] = 50;
["Flashy"] = 7;
}
local Table2 = {
1;
20;
8;
2;
50;
7;
}
function Sorter(a, b)
return a > b
end
table.sort(Table2, Sorter)
for i,v in pairs(Table2) do
print(i, v)
end
These are all numerical keys, so it can be sorted However, I’m curious about why you need the table to be sorted-
If you wish to iterate through it in order via ipairs, you won’t be successful because there are “gaps” in the table (e.g jumps from key 2 to key 7)
If you want to get a sorted array representation of the contents of a dictionary then store all of the key, value pairs in an array.
local array = {}
for key, value in pairs(dictionary) do
array[#array+1] = {key = key, value = value}
end
table.sort(array, function(a, b)
return a.value > b.value
end)
math.randomseed(tick())
local Table1 = {
{90, "A"};
{2, "B"};
{3, "C"};
{20, "D"};
{5, "E"}
}
function Sorter(a, b)
return a[1] > b[1]
end
table.sort(Table1, Sorter)
for i,v in pairs(Table1) do
print(v[1], v[2])
end