table.insert()

Type Function
Library table.*
Return value none
Revision Release 2022.3683
Keywords table, array
See also table.remove()

Overview

Inserts a given value into a table. If a position is given, inserts the value before the element currently at that position.

Syntax

table.insert( t, value )

table.insert( t, pos, value )
t (required)

Table. A table to which the new value will be added. When a table has an element inserted both the size of the array and the element indices are updated.

pos (optional)

Number. The index of the table at which the new element will be inserted. The default value is the length of the table + 1 so that table.insert(t,x) inserts x at the end of table t.

value (required)

The new value to assign to be inserted into the table.

Gotchas

When 2 parameters are provided, the optional parameter pos is ignored.

Note that it is faster to use the length operator: t[#t + 1] = x when inserting new value to a table.

Example

local t = { 1, "jane" }

table.insert( t, "doe" )
--> 1, jane, doe

table.insert( t, 2 )
--> 1, jane, doe, 2 -- notice 'pos' parameter is ignored

table.insert(t, 2, "miss")
--> 1, miss, jane, doe, 2