Lua sort()

siren2077's avatar
Published Sep 17, 2023
Contribute to Docs

The table.sort() function sorts a given table in place.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours

Syntax

table.sort(table, [comp])

The first argument, table, is the table to be sorted. The second argument, comp, is an optional comparison function that specifies the sorting order. If comp is not provided, the default less-than operation is used.

Example

In this example, there is a table named numbers. The table.sort() function is used to sort the table in ascending order.

local numbers = {5, 3, 1, 4, 2}
table.sort(numbers)
for i, v in pairs(numbers) do
print(v)
end

The code results in the following output:

1
2
3
4
5

All contributors

Contribute to Docs

Learn Lua on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours