Reputation: 129
Tried out some different solutions, what im trying to do is find a good fast, and not to performance hungry way of sorting an array in lua that uses named keys, i know named keys is not supported, and there needs to be some sort of change to valued keys insted for this to happen.
Data Structure
[item] => table: 00000275C74CF140 {
[bread] => table: 00000275C74CE1C0 {
[quantity] => 415
[item] => bread
[label] => Quark
}
[silencer] => table: 00000275C74CE1C0 {
[quantity] => 5
[item] => silencer
[label] => Goat
}
}
What i want is to sort by label so i get a print out in the correct order.
So if bread had a label of Quark, and silencer a label of Goat.
It should be Goat Quark
I know how to get around it and sort by the named key by now i figured that one out.
But im not sure what i can do to actually sort by label insted, and get it sorted this way.
Hope that someone is able to lead me in the right direction on what to do here.
Upvotes: 1
Views: 129
Reputation: 28974
Put the elements you want to sort into a list.
local list = {}
for k,v in pairs(yourTable) do
table.insert(list, v)
end
Then sort that list using table.sort
table.sort (list [, comp]) Sorts list elements in a given order, in-place, from list[1] to list[#list]. If comp is given, then it must be a function that receives two list elements and returns true when the first element must come before the second in the final order (so that, after the sort, i < j implies not comp(list[j],list[i])). If comp is not given, then the standard Lua operator < is used instead. Note that the comp function must define a strict partial order over the elements in the list; that is, it must be asymmetric and transitive. Otherwise, no valid sort may be possible. The sort algorithm is not stable: elements considered equal by the given order may have their relative positions changed by the sort.
table.sort(list, function(a,b) return a.label < b.label end)
Upvotes: 1