Sorting By Functions in Lua
Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Lua.
In this Lua version, we use the table.sort
function to sort our collections. This function takes a table and an optional comparison function as arguments.
For sorting strings by length, we define a compare_lengths
function that compares the lengths of two strings using the #
operator, which returns the length of a string in Lua.
For sorting custom objects (like the Person
objects in the example), we use an anonymous function directly in the table.sort
call. This function compares the age
fields of two Person
objects.
Note that Lua uses tables as its primary data structure, so we use tables where the original Go code used slices.
To run this program, save it as sorting_custom.lua
and use:
This example demonstrates how to implement custom sorting in Lua, both for built-in types like strings and for custom objects. The table.sort
function in Lua is quite flexible and can be used with any comparison function that returns true when its first argument should come before its second argument in the sorted order.