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 milkThe 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: 95Challenge
EasyCreate 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 elementThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators 2 Relational & Logic
Equality OperatorsRelational OperatorsThe 'and' OperatorThe 'or' OperatorThe 'not' OperatorShort-Circuit EvaluationTruthy and Falsy ValuesRecap - Simple Logic7Basic Conditional Logic
The if-then StatementThe if-then-else StatementThe elseif StatementRecap - Treasure Chest10Tables Part 1: List-Style
What is a Table?Creating a TableAccessing Elements by IndexModifying Elements by IndexThe Length Operator '#'table.insert()table.remove()Recap - Manage Party Members2Variables and Data Types
What is a Variable?NumbersStringsBooleansThe Value 'nil'The type() FunctionNaming ConventionsRecap - Character Profile5Basic Output
Printing LiteralsPrinting VariablesPrinting Multiple ValuesCombining Strings & VariablesThe tostring() FunctionInputCastRecap - Status ReportRecap - Till 1208String Manipulation Basics
string.len()string.upper & string.lowerstring.sub()string.rep()string.find()Recap - Format Username3Operators 1 Arithmetic & Conc
Arithmetic OperatorsModulo OperatorExponentiation OperatorString ConcatenationOperator PrecedenceRecap - Simple Calculations6Project: Character Stats Disp
Welcome MessageDeclare Character Stats9Functions Basics
Declaring a FunctionCalling a FunctionFunctions with ParametersFunctions with Multiple ParamsThe 'return' StatementRecap - Area Calculator