Sorting, unpack and pack
table.sort orders a list, and unpack and pack convert between tables and value lists.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Sorting a list that mixes numbers and strings
- Calling unpack directly as in Lua 5.1
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: