table.sort()
The table.sort()
function sorts the elements of a table in place. It can take an optional comparison function to customize the sorting behavior.
Syntax
table.sort(tableData, comparator)
Parameters
- Name
tableData
- Type
- table
- Description
The table containing the elements to be sorted.
- Name
comparator
- Type
- function
- Description
A function that defines the sort order. It should take two arguments and return
true
if the first argument should come before the second.
Return
The function returns the sorted table (the same table passed as tableData
).
Description
The table.sort()
function sorts the elements of a table in ascending order by default. If a comparator function is provided, it will be used to determine the order of the elements. This function modifies the original table.
Examples
Sorting a table in ascending order
local numbers = {5, 3, 8, 1, 4}
table.sort(numbers)
print(table.concat(numbers, ", ")) -- Output: 1, 3, 4, 5, 8
Sorting a table in descending order using a comparator
local function compareDescending(a, b)
return a > b
end
local values = {5, 3, 8, 1, 4}
table.sort(values, compareDescending)
print(table.concat(values, ", ")) -- Output: 8, 5, 4, 3, 1
Sorting a table of strings
local fruits = {"Banana", "Apple", "Cherry"}
table.sort(fruits)
print(table.concat(fruits, ", ")) -- Output: Apple, Banana, Cherry
Sorting a table of tables based on a specific key
local people = {
{name = "Alice", age = 30},
{name = "Bob", age = 25},
{name = "Charlie", age = 35}
}
table.sort(people, function(a, b)
return a.age < b.age
end)
for _, person in ipairs(people) do
print(person.name .. ": " .. person.age)
end
-- Output:
-- Bob: 25
-- Alice: 30
-- Charlie: 35
See also
table.insert()
: Inserts elements into a table, which may be useful after sorting.table.remove()
: Removes elements from a table, which may be necessary when managing sorted data.