What is a Variable?
Part of the Fundamentals section of Coddy's Lua journey — lesson 4 of 90.
Variables: Think of a variable as a labeled container that can hold information. Just like you might put items in a box and write a label on it to remember what's inside, variables let you store data and give it a meaningful name so you can use it later.
In Lua, creating a variable is simple. You write the name you want to give it, followed by an equals sign, and then the value you want to store:
playerScore = 100This creates a variable called playerScore and stores the number 100 in it. Now whenever you need to use that score in your program, you can simply refer to it by name instead of typing 100 every time.
To display a value on the screen, use the print() function. Place the variable name inside the parentheses and Lua will output its value:
playerScore = 100
print(playerScore)This will output 100 to the screen. Notice that when printing a variable, you write its name without quotes — quotes are used for text (strings), not for variable names.
Challenge
EasyCreate a variable called gameLevel and assign it the number 5. Then print the value of this variable.
Cheat sheet
Variables are labeled containers that store information. In Lua, create a variable by writing its name, followed by an equals sign, and then the value:
playerScore = 100You can then use the variable name to refer to its stored value throughout your program.
Use print() to display a value in the output. Pass the variable name inside the parentheses to print its stored value:
print(playerScore) -- outputs: 100Try it yourself
-- TODO: Write your code hereThis 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 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