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}
.
table.sort(tableVal)
tableVal
: This is the table that will be sorted.It returns a table sorted in ascending order.
In the snippet below, we will see a sorted table:
--declare some tables to sortcities = {"paris","1000","tokyo","madrid","200","lagos","boston"}--print the unsorted tablesprint("unsorted table")for key,value in ipairs(cities) doprint(key,value)end--sort the tablestable.sort(cities)print("sorted table")--print the sorted tablesfor key,value in ipairs(cities) doprint(key,value)end
Note: In the table shown in the code snippet above, the number strings will always be at the top of the sort.
cities
.cities
.