Lua Table Functions
Table functions are ready-made tools that sort a table or join its values into one string. table.sort puts values in order and table.concat builds a string from an array.
Sort puts numbers in order
table.sort changes the table itself. An ipairs loop prints the new order.
local nums = {30, 10, 20}
table.sort(nums)
for i, v in ipairs(nums) do
print(v)
endConcat joins values into one string
table.concat joins the array with the separator between each pair of values. Each print shows one whole joined string.
local words = {"Lua", "is", "fun"}
local line = table.concat(words, " ")
print(line)
print(table.concat(words, "-"))Sorted keys print in order
The keys are first collected into an array and sorted. The loop then prints each value by its sorted key.
local prices = {milk = 3, bread = 2, eggs = 4}
local keys = {}
for k, v in pairs(prices) do
table.insert(keys, k)
end
table.sort(keys)
for i, k in ipairs(keys) do
print(k .. ": " .. prices[k])
endExample
local scores = {70, 95, 80}
table.sort(scores)
for i = #scores, 1, -1 do
print(scores[i])
endKey points
- table.sort: table.sort(t) orders the values in t from smallest to largest.
- In place: Sorting changes the table itself and returns nothing.
- Strings: table.sort puts strings in alphabet order from A to Z.
- table.concat: table.concat(t, sep) joins the array values into one string with sep between them.
- Sorted keys: Collect the keys of a dictionary into an array, sort that array, and then loop to print values in key order.
In this example, table.sort puts the scores in the table in rising order, 70, 80 and 95. The numeric for loop then counts down from the last slot to the first. That prints the scores from highest to lowest without changing the table again.
Note
table.sort works on the array part of a table, so dictionary values are reached through their sorted keys.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
After local nums = {3, 1, 2} and table.sort(nums), what does print(nums[1]) show?