How to pass a function to table.sort?

I’m building a class that holds an array that needs sorting.
I want the class to hold the sorting function, so that I can change the sorting conditions.
I’ve tried it with table.sort like this:

T = class()

function T:init()
    self.queue = {4,3,5,7,2,56,8}
end

function T:sort()
    table.sort(self.queue,self.compare) 
end

function T:compare(a,b)
    print(a,b) -- print statement to check the incoming values
    return a>b
end

then in Main:

thingy = T()
thingy:sort()

What happens is that I get an error stating that the second argument to the compare function is nil.
I’ve checked it and it seems that the first argument gets passed, but the second is nil.
changing self.compare to self:compare also doesn’t work

How do I do this, apart from building my own sorting routine?

The problem is your compare function actually takes three arguments: self, a, b

Because it’s a method rather than a function (i.e. specified with the colon : operator) it will always take self as its first argument.

You can update your sort function to take this into account:

function T:sort()
    table.sort( self.queue, function(a,b) return self:compare(a,b) end ) 
end

```


The above wraps your compare function into a two-argument anonymous function.

Or you can write your comparator function as a non-method function:

function compare(a,b)
    return a > b
end

```

Ok, cool.
I’ll try the first option, I like to keep everything inside this class.
Thanks a lot!

How about:

T = class()

function T:init()
    self.queue = {4, 3, 5, 7, 2, 56, 8}
    self.compare = function (a, b)
        print(a, b)
        return a > b
    end
end

function T:sort()
    table.sort(self.queue, self.compare) 
end

```

.@mpilgrem’s is neater than mine. I would go with that.

Why not:


function T:sort()
    table.sort(self.queue, function(a, b)
        return a > b
    end)
end

Then you don’t even need your comparator function to be a part of your object.