Table Functions: insert, remove, concat, sort

You can add to a list with t[#t + 1] = value. But Lua also has a table library, a set of ready-made functions for common list jobs. Four of them cover most of what you will need.

table.insert and table.concat

local queue = {"Alice", "Bob"}
table.insert(queue, "Emma")
print(table.concat(queue, ", "))

Output:

Alice, Bob, Emma

table.insert(t, value) adds the value to the end of the table.

table.concat(t, separator) joins all the values into one string, with the separator between them. It is the easiest way to print a whole list on one line.

table.insert can also take a position. Then the value goes in at that position, and every value after it moves one place to the right:

table.insert(queue, 1, "Dan")
print(table.concat(queue, ", "))

Output:

Dan, Alice, Bob, Emma

table.remove

table.remove(t, position) takes out the value at that position and returns it. The values after it move one place to the left, so there is no gap. With no position, it removes the last value.

local first = table.remove(queue, 1)
print("Removed: " .. first)
table.remove(queue)
print(table.concat(queue, ", "))

Output:

Removed: Dan
Alice, Bob

Dan was at position 1, so he was removed and returned. Then table.remove(queue) removed Emma from the end.

table.sort

table.sort(t) puts the values in order, smallest first. It changes the table itself, so you do not need to save a result.

local nums = {40, 10, 25}
table.sort(nums)
print(table.concat(nums, " "))

Output:

10 25 40

To sort in a different order, pass a comparison function as the second argument. It gets two values, a and b, and returns true when a should come first. This one sorts from largest to smallest:

table.sort(nums, function(a, b)
    return a > b
end)
print(table.concat(nums, " "))

Output:

40 25 10

This is an anonymous function passed as an argument, as you saw in the Functions as Values lesson.

Avoid gaps in a list

These functions, and #, expect a list with no gaps: values at 1, 2, 3 and so on, with nothing missing. Here is what happens with a gap:

local t = {"a", "b", "c"}
t[7] = "x"
print(t[7])
print(#t)
print(table.concat(t, " "))

Output:

x
3
a b c

The value at index 7 is in the table, as the first line shows. But # and table.concat ignore it, because indexes 4 to 6 are empty. To keep a list correct, add with table.insert and take out with table.remove.

In the exercise, add numbers to a queue with table.insert, remove the first one with table.remove, and print the rest.