Sorting in Lua
Lua’s standard library doesn’t include a built-in sorting function for tables, but we can easily implement one. We’ll look at sorting for basic types first.
-- In Lua, we'll use a custom function to sort tables
local function sortTable(t, compareFunc)
table.sort(t, compareFunc)
end
-- Main function to demonstrate sorting
local function main()
-- Sorting strings
local strs = {"c", "a", "b"}
sortTable(strs)
print("Strings:", table.concat(strs, " "))
-- An example of sorting numbers
local nums = {7, 2, 4}
sortTable(nums)
print("Numbers:", table.concat(nums, " "))
-- We can also check if a table is already in sorted order
local function isSorted(t)
for i = 1, #t - 1 do
if t[i] > t[i + 1] then
return false
end
end
return true
end
local s = isSorted(nums)
print("Sorted:", s)
end
-- Run the main function
main()In this Lua example:
We define a
sortTablefunction that uses Lua’s built-intable.sortfunction. By default, it sorts in ascending order.We create a
mainfunction to demonstrate the sorting functionality.For sorting strings, we create a table of strings and sort it using our
sortTablefunction.For sorting numbers, we create a table of numbers and sort it in the same way.
To check if a table is sorted, we implement an
isSortedfunction that iterates through the table and checks if each element is less than or equal to the next one.We print the results using
table.concatto convert the sorted tables to strings.
When you run this script, you should see output similar to this:
$ lua sorting.lua
Strings: a b c
Numbers: 2 4 7
Sorted: trueThis example demonstrates basic sorting in Lua. Note that Lua’s tables are more flexible than Go’s slices, as they can contain mixed types. For more complex sorting scenarios, you might need to provide custom comparison functions to the table.sort method.