Code: Select all
table.sort(t, function(a,b) return a>b end)
Code: Select all
table.sort(t, function(a,b) return a>b end)
Code: Select all
table.sort()
Code: Select all
Lua 5.2.1 Copyright (C) 1994-2012 Lua.org, PUC-Rio
> test = {
>> {1, 1},
>> {1, 2},
>> {2, 1},
>> {2, 2}}
> table.sort(test, function(a, b) return a[1] > b[1] or a[2] > b[2] end)
> for i, v in ipairs(test) do print(v[1], v[2]) end
2 2
2 1
1 2
1 1
I'm not understanding this. Can you give an example? i.e. an "unsorted" table vs the same table sorted the way you want.Jasoco wrote:Is it possible to sort a table by one parameter, then sub-sort it again by another parameter? And possibly again and again if needed?
Jasoco wants to sort a table by a parameter. Then afterwards he wants to sort all entries, that are equal in one entry, with respect to another entry. This is also called Lexicographical order http://en.wikipedia.org/wiki/Lexicographic_order.kikito wrote:I'm not understanding this. Can you give an example? i.e. an "unsorted" table vs the same table sorted the way you want.Jasoco wrote:Is it possible to sort a table by one parameter, then sub-sort it again by another parameter? And possibly again and again if needed?
Ow! Then you just write the sorting conditions in your sorting function. You can sort by 1,2 or any other properties.micha wrote:Then afterwards he wants to sort all entries, that are equal in one entry, with respect to another entry. This is also called Lexicographical order http://en.wikipedia.org/wiki/Lexicographic_order.
Code: Select all
people = { { name='Bob', age=21 }, { name='Peter', age=18 }, { name='Andrew', age=18 } }
Code: Select all
table.sort(people, function(a,b) return a.age < b.age end) -- Peter, Andrew, Bob
Code: Select all
table.sort(people, function(a,b) return a.name < b.name end) -- Andrew, Bob, Peter
Code: Select all
table.sort(people, function(a,b)
if a.age == b.age then return a.name < b.name end
return a.age < b.age
end) -- This will give you Andrew, Peter, Bob
Code: Select all
table.sort(test, function(a, b) return a[1] > b[1] or a[2] > b[2] end)
-- return 2 > 3 or 2 > 1
-- return false or true
-- return true
You only want to look at the second condition if the first condition would compare equal.table.sort(test, function(a, b) if a[1] == b[1] then return a[2] > b[2] end return a[1] > b[1] end
-- if 2 == 3 then return 2 > 1 end return 2 > 3
-- if false then return true end return false
-- return false
Code: Select all
a or b
Code: Select all
table.sort(test, function(a, b) return a[1] > b[1] or (a[1] == b[1] and a[2] > b[2]) end)
Users browsing this forum: Ahrefs [Bot], Roland Chastain and 199 guests