🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Sorting Tables

Sorting a table means putting its elements in a chosen order. table.sort does the arranging when you give it a rule for comparing two elements.

A comparator decides the order

table.sort takes a comparator as its second argument. This comparator sorts numbers from largest to smallest.

local scores = {5, 2, 9, 1}
table.sort(scores, function(a, b) return a > b end)
print(table.concat(scores, ", "))

Records sort by one field

The comparator can compare a single field on each record. Here scores decide the order, highest first.

local players = {
  {name = "Mia", score = 40},
  {name = "Leo", score = 90},
  {name = "Ana", score = 70},
}
table.sort(players, function(a, b) return a.score > b.score end)
for i = 1, #players do
  print(players[i].name, players[i].score)
end

Equal keys keep only their group

Sorting groups equal scores together. It does not promise which equal record comes first, so this snippet prints scores only.

local items = {
  {name = "A", score = 10},
  {name = "B", score = 20},
  {name = "C", score = 10},
  {name = "D", score = 20},
}
table.sort(items, function(a, b) return a.score < b.score end)
for i = 1, #items do
  print(items[i].score)
end

Example

local products = {
  {name = "Lamp", price = 45},
  {name = "Chair", price = 120},
  {name = "Mug", price = 12},
}
table.sort(products, function(a, b) return a.price > b.price end)
for i = 1, #products do
  print(products[i].name, products[i].price)
end

Key points

  • Comparator: a comparator is a function that takes two values and returns true when the first should come before the second.
  • Default order: table.sort without a comparator sorts values in ascending order.
  • Records: a record is a table that groups named fields for one item.
  • Field sort: sorting records by a field means the comparator compares that field on both records.
  • Descending order: a descending comparator returns true when the first value is larger than the second.

In this example, a list of products is built with a name and a price for each item. table.sort orders the list by price from highest to lowest. The loop then prints each name with its price in the new order.

Note

Lua table.sort is not stable, so equal keys may change order.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does table.sort do when its comparator returns true for a pair?