What is the table.sort() method in Lua?

Overview

Tables in are objects in Lua. They are made using the {} constructor. In Lua, the only available data structure is the table structure that accepts and creates different types, such as arrays, and dictionaries. The size of tables is not fixed and tables can grow to the required size.

Numerous operations can be performed on tables. One such operation is sorting, which can be done with the table.sort() method.

The table.sort() method is a table manipulation method that arranges the table in ascending order. This means that smaller values are sorted to smaller indexes. For instance, if a table A = {d,c,b,f,e} is to be sorted, then the table.sort() method would return A as {b,c,d,e,f}.

Syntax

table.sort(tableVal)

Parameter

  • tableVal: This is the table that will be sorted.

Return value

It returns a table sorted in ascending order.

Example

In the snippet below, we will see a sorted table:

--declare some tables to sort
cities = {"paris","1000","tokyo","madrid","200","lagos","boston"}
--print the unsorted tables
print("unsorted table")
for key,value in ipairs(cities) do
print(key,value)
end
--sort the tables
table.sort(cities)
print("sorted table")
--print the sorted tables
for key,value in ipairs(cities) do
print(key,value)
end

Explanation

Note: In the table shown in the code snippet above, the number strings will always be at the top of the sort.

  • Line 3: We create a table, cities.
  • Lines 6–9: We print all values in the unsorted table.
  • Line 12: We sort the table, cities.
  • Lines 17–19: We print all values in the sorted table.

Free Resources