Menu
Coddy logo textTech

table.insert()

Part of the Fundamentals section of Coddy's Lua journey — lesson 61 of 90.

The table.insert() function adds a new element to the end of a list-style table. Here's the basic syntax:

local tasks = {"homework", "shopping"}
table.insert(tasks, "cooking")
print(tasks[3])  -- outputs: cooking

When you use table.insert(), it automatically places the new element at the next available position and increases the table's length. This means you don't have to worry about calculating the correct index - Lua handles it for you.

local players = {"Alice", "Bob"}
print(#players)  -- outputs: 2
table.insert(players, "Charlie")
print(#players)  -- outputs: 3
challenge icon

Challenge

Easy

Create a quest management system that demonstrates adding new tasks to an adventure log. First, create a table named questLog containing exactly three string values: "Find the ancient artifact", "Defeat the dragon", and "Rescue the villagers". After creating the table, use table.insert() to add a new quest "Collect rare herbs" to the end of the quest log. Finally, print the fourth element of the table to confirm the new quest was added successfully.

Cheat sheet

The table.insert() function adds a new element to the end of a list-style table:

local tasks = {"homework", "shopping"}
table.insert(tasks, "cooking")
print(tasks[3])  -- outputs: cooking

The function automatically places the new element at the next available position and increases the table's length:

local players = {"Alice", "Bob"}
print(#players)  -- outputs: 2
table.insert(players, "Charlie")
print(#players)  -- outputs: 3

Try it yourself

-- TODO: Write your code here
-- Create the questLog table with the three initial quests
-- Add the new quest using table.insert()
-- Print the fourth element
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals