insert()

Anonymous contributor's avatar
Anonymous contributor
Published Sep 20, 2023
Contribute to Docs

The .insert() method inserts a value in a table at a specified index.

Syntax

table.insert(someTable, index, value)

The value is inserted at index. If index is not provided, value is inserted at the end of someTable. The function returns the modified, original table.

Stacks, queues, and double queues can be implemented in this way.

Example

Adding iPhone at the end of apple_products table:

apple_products = {"Macbook", "Watch", "iPad"}
table.insert(apple_products, "iPhone")
for key, value in pairs(apple_products) do
print(key, value)
end

The code above results in the following output:

Macbook
Watch
iPad
iPhone

All contributors

Contribute to Docs

Learn Lua on Codecademy