Table
table.sort
Shared
Sorts table elements in-place
Syntax
table.sort(input, comparison = nil)Parameters
| Type | Name | Description |
|---|---|---|
table | input | Table to be sorted |
function | comparison | Comparison function compare(a, b) - used for manipulating sorting algorithm |
Returns
| Type | Name | Description |
|---|
Examples
--Sort numbers ascending (default)
local nums = {5, 2, 8, 1, 9}
table.sort(nums)
engine.print(table.concat(nums, ", ")) --1, 2, 5, 8, 9--Sort numbers descending
local nums = {5, 2, 8, 1, 9}
table.sort(nums, function(a, b) return a > b end)
engine.print(table.concat(nums, ", ")) --9, 8, 5, 2, 1--Sort strings alphabetically
local words = {"zebra", "apple", "mango", "banana"}
table.sort(words)
engine.print(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(table.concat(words, ", ")) --a, hi, hello, world--Sort case-insensitive
local names = {"Bob", "alice", "Charlie", "david"}
table.sort(names, function(a, b)
return string.lower(a) < string.lower(b)
end)
engine.print(table.concat(names, ", ")) --alice, Bob, Charlie, david--Sort mixed case strings
local items = {"Apple", "banana", "Cherry", "date"}
table.sort(items, function(a, b)
return string.lower(a) < string.lower(b)
end)
engine.print(table.concat(items, ", "))