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:

  1. We define a sortTable function that uses Lua’s built-in table.sort function. By default, it sorts in ascending order.

  2. We create a main function to demonstrate the sorting functionality.

  3. For sorting strings, we create a table of strings and sort it using our sortTable function.

  4. For sorting numbers, we create a table of numbers and sort it in the same way.

  5. To check if a table is sorted, we implement an isSorted function that iterates through the table and checks if each element is less than or equal to the next one.

  6. We print the results using table.concat to 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: true

This 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.