lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello mnip
 
Thanks for the tip, both solutions are neat. As my real code is a bit more complex than I posted due to having multiple sort criteria and functions I went with the sort reverser idea you suggested. Its implemented and working perfectly now, thanks once again.
 
P.S  A sort direction reverser must be a pretty common requirement, but Googling this question found nothing. This would be very useful little snippet to add to the Lua Wiki/Doc pages
 
Regards Geoff

 
> Date: Sat, 28 Mar 2015 00:36:18 +0300
> From: 14@mniip.com
> To: lua-l@lists.lua.org
> Subject: Re: Question on table sorting
>
> 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 */
>