Sorting Lists in Lua


One very common operation on lists is sorting them. Lua's table library contains the table.sort function

local x = {
    "b",
    "e",
    "a",
    "d",
    "c",
}

Default Sort

-- list is sorted in-place
table.sort(x)

print(x[1]) -- a
print(x[2]) -- b
print(x[3]) -- c
print(x[4]) -- d
print(x[5]) -- e

Sorting in Reverse

-- list is sorted in-place
table.sort(x, function(a, b)
    return a > b
end)

print(x[1]) -- e
print(x[2]) -- d
print(x[3]) -- c
print(x[4]) -- b
print(x[5]) -- a

Random Order

local math = require("math")

-- list is sorted in-place
table.sort(x, function(a, b)
    return math.random() > 0.5
end)

print(x[1]) -- d
print(x[2]) -- a
print(x[3]) -- b
print(x[4]) -- c
print(x[5]) -- e