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.
-- We'll use the table.sort function for sorting
local table = require("table")
-- Helper function to compare string lengths
local function compare_lengths(a, b)
return #a < #b
end
local function main()
local fruits = {"peach", "banana", "kiwi"}
-- Sort fruits by length using our custom comparison function
table.sort(fruits, compare_lengths)
print(table.concat(fruits, ", "))
-- We can use the same technique to sort a table of custom objects
local Person = {}
Person.__index = Person
function Person.new(name, age)
return setmetatable({name = name, age = age}, Person)
end
local people = {
Person.new("Jax", 37),
Person.new("TJ", 25),
Person.new("Alex", 72)
}
-- Sort people by age
table.sort(people, function(a, b)
return a.age < b.age
end)
-- Print sorted people
for _, person in ipairs(people) do
print(string.format("%s: %d", person.name, person.age))
end
end
main()
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:
$ lua sorting_custom.lua
kiwi, peach, banana
TJ: 25
Jax: 37
Alex: 72
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.