I am attempting to sort an advanced table, but not succeeding.
Here is what my table structure looks like:
{
["12345"] = {12345, "Something", {"Stuff"}},
["523544"] = {523544, "Something", {"Stuff"}},
["6744"] = {6744, "Something", {"Stuff"}},
["146"] = {146, "Something", {"Stuff"}},
["724572"] = {724572, "Something", {"Stuff"}},
["54"] = {54, "Something", {"Stuff"}},
["146"] = {146, "Something", {"Stuff"}},
["146"] = {146, "Something", {"Stuff"}},
["12345"] = {12345, "Something", {"Stuff"}},
["44"] = {44, "Something", {"Stuff"}},
}
and I would like to sort it from greatest to least like so:
{
["724572"] = {724572, "Something", {"Stuff"}},
["523544"] = {523544, "Something", {"Stuff"}},
["12345"] = {12345, "Something", {"Stuff"}},
["12345"] = {12345, "Something", {"Stuff"}},
["6744"] = {6744, "Something", {"Stuff"}},
["146"] = {146, "Something", {"Stuff"}},
["146"] = {146, "Something", {"Stuff"}},
["146"] = {146, "Something", {"Stuff"}},
["54"] = {54, "Something", {"Stuff"}},
["44"] = {44, "Something", {"Stuff"}},
}
I am running into a few problems here.
As for why the indexes are strings, if I do table[623258195] = "Example", the table would create 623258195 indexes, causing my program to crash.
As for why the values are tables, it stores other important information, which is what the 2nd and 3rd values in the table are, the 1st being an number form of the index.
I hope I'm being clear, and I'm sorry if this would be considered a duplicate question, I have not found anything in the last hour of searching that has assisted me.
You'll need to modify your data structure, to support multiple values with the same id/key:
{
[12345] = {
{12345, "foo", {"bar"}}, -- You'll probably want to sort these somehow.
{12345, "baz", {"qux"}}
},
[123] = {
{123, "foo", {"bar"}}
}
}
You can use table.sort(tbl, f), along with an index table:
local unsorted = {} -- Data, in your format, inside this table.
local index = {} -- Table which will contain sorted keys (then you loop over this, get unsorted[k])
for k in pairs(unsorted) do
index[#index+1] = k -- Populate the keys to sort.
end
table.sort(index, function(a, b)
return b < a -- Order highest to lowest, instead of lowest - highest (default)
end)
Here's the full code sample, and results. http://ideone.com/thE1zP
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With