Main Content

Sorting in lua - specifying your own sort routine

Archive - Originally posted on "The Horse's Mouth" - 2008-07-05 19:25:18 - Graham Ellis

In Lua, the table.sort function allows you to sort a table and by default is sorts into the order that's given back by the < operator on each of the objects to be sorted. If you want to override this behaviour, you can pass the name of a function into Lua's sort and it will call this function each time a comparison is needed.

In order to help demonstrate this, I wrote a sample program with my own sort routine which I called "mysort" - as a direct replacement for table.sort with two parameters - table and function.

You can see the source code here.