[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Question on table sorting
- From: mniip <14@...>
- Date: Sat, 28 Mar 2015 00:36:18 +0300
On 03/28/2015 12:32 AM, Geoff Smith wrote:
> Hi
>
> Quick question on a custom table sort.
>
> I have a custom sort function working correctly e.g. table.sort(myTab,
> customCompareFunc)
>
> Then I thought I would like the option of sorting in ascending or descending
> directions, so I would need to pass in a dirn argument into my
> custom sort function. I cant see how I could do that unless it was a nasty
> global.
> Is there an elegant way to pass in an argument to the customCompare ?
>
> Thanks for any tips
>
> Geoff
You could make a function return another function, which in turn gets fed to
table.sort like:
function customCompare(dir)
return function(a, b)
if dirn then
return a > b
else
return a < b
end
end
end
table.sort(t, customCompare(true))
table.sort(t, customCompare(false))
Or you could create a sort reversing combinator, that can flip the direction of
arbitrary sorters:
function reverse(f)
return function(a, b)
return f(b, a)
end
end
table.sort(t, customCompare)
table.sort(t, reverse(customCompare))
--
/* mniip */