Vital.sandbox
Table

table.insert

Shared

Inserts an element into a table at a specified position


Syntax

table.insert(input, value, index = table.len(input) + 1)

Parameters

TypeNameDescription
tableinputTable to be inserted into
anyvalueValue to insert
intindexIndex where the element should be inserted

Returns

TypeNameDescription

Examples

Append an element to the end of a table
local t = {1, 2, 3}
table.insert(t, 4)

engine.print("info", table.concat(t, ", ")) --'1, 2, 3, 4'
Insert an element at a specific position
local t = {"a", "c", "d"}
table.insert(t, 2, "b")

engine.print("info", table.concat(t, ", ")) --'a, b, c, d'
Insert an element at the beginning
local t = {2, 3, 4}
table.insert(t, 1, 1)

engine.print("info", table.concat(t, ", ")) --'1, 2, 3, 4'
Build an array dynamically with a loop
local numbers = {}
for i = 1, 5 do
    table.insert(numbers, i * 10)
end

engine.print("info", table.concat(numbers, ", ")) --'10, 20, 30, 40, 50'
Append multiple strings to a table
local words = {"hello"}
table.insert(words, "world")
table.insert(words, "lua")

engine.print("info", table.concat(words, " ")) --'hello world lua'
Insert an element at a middle position
local colors = {"red", "green", "blue"}
table.insert(colors, 2, "yellow")

engine.print("info", table.concat(colors, ", ")) --'red, yellow, green, blue'
Insert into an empty table
local t = {}
table.insert(t, "first")

engine.print("info", t[1]) --'first'
Push elements onto a stack
local stack = {}
table.insert(stack, "item1")
table.insert(stack, "item2")
table.insert(stack, "item3")

engine.print("info", #stack) --3
Build a list by inserting from another table
local names = {}
local inputs = {"Alice", "Bob", "Charlie"}

for _, name in ipairs(inputs) do
    table.insert(names, name)
end
Insert a table as a nested element
local lists = {{1, 2}, {3, 4}}
table.insert(lists, {5, 6})

engine.print("info", #lists) --3

On this page