Inserting, removing and joining
The table library adds and removes items and joins them into a string.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Swapping the position and value arguments in table.insert
- Calling table.concat on a table that contains tables or booleans
- 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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: