Vital.sandbox
Table

table.sort

Shared

Sorts table elements in-place


Syntax

table.sort(input, comparison = nil)

Parameters

TypeNameDescription
tableinputTable to be sorted
functioncomparisonComparison function compare(a, b) - used for manipulating sorting algorithm

Returns

TypeNameDescription

Examples

Sort numbers in ascending order
local nums = {5, 2, 8, 1, 9}
table.sort(nums)

engine.print("info", table.concat(nums, ", ")) --'1, 2, 5, 8, 9'
Sort numbers in descending order
local nums = {5, 2, 8, 1, 9}
table.sort(nums, function(a, b) return a > b end)

engine.print("info", table.concat(nums, ", ")) --'9, 8, 5, 2, 1'
Sort strings alphabetically
local words = {"zebra", "apple", "mango", "banana"}
table.sort(words)

engine.print("info", table.concat(words, ", ")) --'apple, banana, mango, zebra'
Sort strings by length
local words = {"hi", "hello", "a", "world"}
table.sort(words, function(a, b) return #a < #b end)

engine.print("info", table.concat(words, ", ")) --'a, hi, hello, world'
Sort strings case-insensitively
local names = {"Bob", "alice", "Charlie", "david"}
table.sort(names, function(a, b) 
    return string.lower(a) < string.lower(b) 
end)

engine.print("info", table.concat(names, ", ")) --'alice, Bob, Charlie, david'
Sort mixed-case strings uniformly
local items = {"Apple", "banana", "Cherry", "date"}
table.sort(items, function(a, b)
    return string.lower(a) < string.lower(b)
end)

engine.print("info", table.concat(items, ", ")) --'Apple, banana, Cherry, date'

On this page