Below is a sample table structure of what I am wanting to sort.
Data = {
["C1_RN1::F1"] = {
["class"] = "Hunter",
["name"] = "C1",
["faction"] = "Faction",
["race"] = "Human",
["realm"] = "RN1",
},
["C2_RN1::F1"] = {
["class"] = "Priest",
["name"] = "C2",
["faction"] = "Faction",
["race"] = "Undead",
["realm"] = "RN1",
},
["C3_RN1::F1"] = {
["class"] = "Hunter",
["name"] = "C3",
["faction"] = "Faction",
["race"] = "Human",
["realm"] = "RN1",
}
}
So for example I would like to sort by race alphabetically, and sort all the "Human" race characters by class also alphabetically, and sort any other "races" also by alphabetically independent of another "race".
I know how to sort by just one by dumping all the character names into a 2nd table with the same keys as the data table, and then comparing data in the data table using table.sort and a that compares data with the less than operator such as data[a].race < data[b].race.
This is the function I tried to use to a basic sort, but this doesn't work using Lua 5.1, i get an error saying there should be an = after the <.
local function SortThis()
local temp = {}
for c in pairs(Data) do
table.insert(temp, c);
end
table.sort(temp, function(a, b)
return Data[a].race < RestXP_Data[b].race;
end)
end
Currently there is nothing to sort, as you have associative-array type tables, which will always have arbitrarily ordered keys and values. You can only sort array-like tables (those with numerical indices).
In your comparison function, simply check if your primary comparison is equal, in which case you move on to your secondary comparison (and then tertiary comparison, etc...). If a key comparison is not equal, return the appropriate result for that key (i.e.,
<or>).Note that
table.sortis not stable.If you have a lot of keys to compare, you can loop through them.