table.insert()
The table.insert()
function adds a new value to a table at a specified index. If the index is not specified, the value will be added to the end of the table.
Syntax
table.insert(tableData, value, position)
Parameters
- Name
tableData
- Type
- table
- Description
The table where the value will be inserted.
- Name
value
- Type
- any
- Description
The value to be inserted into the table.
- Name
position
- Type
- number|nil
- Description
Optional. The position in the table where the value should be inserted. If omitted, the value is appended to the end of the table.
Return
The function returns nil
.
Description
The table.insert()
function allows you to add values to a table, either at a specific position or at the end. If you specify an index, the function shifts the current elements to the right to accommodate the new value. This is useful for maintaining order in lists or queues.
Examples
Inserting a value at a specific position
local fruits = {"Apple", "Banana", "Cherry"}
table.insert(fruits, 2, "Orange") -- Inserts "Orange" at index 2
print(table.concat(fruits, ", "))
-- Output: Apple, Orange, Banana, Cherry
Appending a value to the end
local numbers = {1, 2, 3}
table.insert(numbers, 4) -- Appends 4 to the end of the table
print(table.concat(numbers, ", "))
-- Output: 1, 2, 3, 4
Inserting at the beginning of a table
local colors = {"Blue", "Green", "Red"}
table.insert(colors, 1, "Yellow") -- Inserts "Yellow" at the beginning
print(table.concat(colors, ", "))
-- Output: Yellow, Blue, Green, Red
Inserting in an empty table
local emptyTable = {}
table.insert(emptyTable, "First")
print(table.concat(emptyTable, ", "))
-- Output: First
See also
table.remove()
: Removes a value from a table at a specified position.table.concat()
: Concatenates the values of a table into a single string.