Why Use Local Variables?
Part of the Fundamentals section of Coddy's Lua journey. Lesson 85 of 90.
Preventing Name Conflicts: The most important benefit of local variables is that they prevent you from accidentally overwriting other variables with the same name. When you use global variables throughout your program, it's easy to accidentally reuse a variable name and change a value you didn't intend to modify.
score = 100 -- the player's score
function countEnemies()
score = 0 -- meant as a counter just for this function
for i = 1, 3 do
score = score + 1
end
return score
end
countEnemies()
print(score) -- 3: the player's score was overwritten!The function meant to use its own counter, but because score is global, it changed the player's score instead. Adding local gives the function a separate variable that exists only inside it:
function countEnemies()
local score = 0 -- a new variable, only inside this function
for i = 1, 3 do
score = score + 1
end
return score
end
countEnemies()
print(score) -- 100: the global score is untouchedWith local variables, each function and block has its own separate variables, so code in one place can't accidentally change values used somewhere else.
Try it yourself
This lesson doesn't include a code challenge.
This 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 Chest2Variables 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 Username11Tables 2: Dictionary-Style
Key-Value PairsCreating Dictionary-Style TablAccessing - Bracket NotationAccessing with Dot NotationAdding and Modifying PairsRemoving Pairs with nilRecap - Item Properties14Variable Scope
Global VariablesLocal VariablesWhy Use Local Variables?Scope and BlocksRecap - Scope Puzzle3Operators 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 CalculatorPractice on your own: Online Lua compiler