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

Inserting, removing and joining

The table library adds and removes items and joins them into a string.

Inserting, removing and joining

table.insert(t, v) appends and table.insert(t, pos, v) inserts at a position, shifting later items up. table.remove(t) removes and returns the last item, and table.remove(t, pos) removes at a position, shifting items down. table.concat(t, sep) joins strings or numbers with a separator.

Note: table.remove on an empty table returns nil and does not raise an error.

Example: Inserting, removing and joining

lua
local t = {"a", "b", "c"}
table.insert(t, "d")
table.insert(t, 1, "start")
print(table.concat(t, ","))
print(table.remove(t), table.remove(t, 1))
print(table.concat(t, ","), #t)
print(table.remove({}))

-- Output:
-- start,a,b,c,d
-- d	start
-- a,b,c	3
-- nil
Common Mistakes
  1. Swapping the position and value arguments in table.insert
  2. Calling table.concat on a table that contains tables or booleans
  3. Removing items inside a forward loop and skipping elements
Chapter Summary
  • table.insert appends or inserts at a position
  • table.remove returns the removed item
  • table.concat joins with a separator
  • Loop backwards when removing

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.