lua-users home
lua-l archive

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

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
          return a < b
    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)
    table.sort(t, customCompare)
    table.sort(t, reverse(customCompare))

/* mniip */