Menu
Coddy logo textTech

Modifying Elements by Index

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

Modifying an element in a table uses the same square bracket syntax as accessing, but with an assignment operator.

Here's the basic syntax for changing a value:

local items = {"milk", "bread", "eggs"}
items[1] = "almond milk"  -- changes first item
print(items[1])  -- outputs: almond milk

The assignment works just like with regular variables - you specify which position you want to change using the index in square brackets, then use the equals sign to assign the new value.

local scores = {85, 92, 78}
scores[2] = 95  -- update the second score
print(scores[2])  -- outputs: 95
challenge icon

Challenge

Easy

Create a game settings management system that demonstrates table element modification. First, create a table named gameSettings containing exactly three string values: "easy", "on", and "high". After creating the table, modify the first element by changing it from "easy" to "hard". Finally, print the modified first element to confirm the change.

Try it yourself

-- TODO: Write your code here
-- Create the gameSettings table with the required values
-- Modify the first element
-- Print the modified first element
quiz iconTest yourself

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

All lessons in Fundamentals