← Back to Lua Course | Chapter 4: Tables | Lesson 7 of 7

Sorting, unpack and pack

table.sort orders a list, and unpack and pack convert between tables and value lists.

In this page:

  1. Sorting, unpack and pack

Sorting, unpack and pack

table.sort(t, comp) sorts in place with an optional comparison function that returns true when the first argument should come first. table.unpack(t) returns the items as separate values, and table.pack(...) collects values into a table with an n field holding the count. In Lua 5.3 unpack lives in the table library.

Note: The comparison function must be consistent, so use < or > rather than <= or >=.

Example: Sorting, unpack and pack

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

local words = {"pear", "fig", "banana"}
table.sort(words, function(a, b) return #a < #b end)
print(table.concat(words, " "))

print(table.unpack({1, 2, 3}))
local packed = table.pack("x", nil, "z")
print(packed.n, #packed >= 1)

-- Output:
-- 1 2 5 8
-- 8 5 2 1
-- fig pear banana
-- 1	2	3
-- 3	true
Common Mistakes
  1. Sorting a list that mixes numbers and strings
  2. Calling unpack directly as in Lua 5.1
  3. Writing a comparison function that returns true for equal items
Chapter Summary
  • table.sort sorts in place
  • A comparison function customises the order
  • table.unpack spreads a table
  • table.pack keeps the count in n

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.