table.insert

Inserts a new item into a numerically-keyed table

Prototype

table.insert (t, pos, value)

Description

Inserts the value at (optional) position 'pos', renumbering existing elements if necessary to make room. Thus the new element becomes the one with index 'pos'.

If called with 2 arguments, the value is inserted at n+1, that is, the end of the table.

t = { "the", "quick", "brown", "fox" }
table.insert (t, 2, "very") -- new element 2
table.insert (t, "jumped")  -- add to end of table
table.foreachi (t, print)

 -->

1 the
2 very
3 quick
4 brown
5 fox
6 jumped
The Lua authors recommend using the idiom "#t + 1" to insert to the end of a table nowadays. For example:

t = {}
t [#t + 1] = "hello, "
t [#t + 1] = "world"
Note that for other keys (eg. strings) you simply assign to the table item to insert it. For example:

t = {}
t.foo = "bar"    -- insert key "foo"
t ["Nick Gammon"] = 42  -- insert key "Nick Gammon"

Lua functions

Topics