Lua 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.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours

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

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
    • Beginner Friendly.
      4 hours