Arithmetic Operators
Part of the Fundamentals section of Coddy's Lua journey — lesson 12 of 90.
Arithmetic operators are symbols that tell Lua to perform mathematical operations on numbers.
Lua provides four basic arithmetic operators that work just like in mathematics:
-- Addition
result = 10 + 5 -- result is 15-- Subtraction
result = 10 - 3 -- result is 7-- Multiplication
result = 4 * 6 -- result is 24-- Division
result = 15 / 3 -- result is 5Challenge
EasyCalculate the total cost of purchasing two items in a game shop. Create variables for the price of each item, then use arithmetic operators to find the total cost.
Create the following variables:
swordPricewith the value25shieldPricewith the value18
Calculate the total cost by adding these two prices together and store the result in a variable called totalCost. Then print the total cost.
Cheat sheet
Lua provides four basic arithmetic operators for mathematical operations:
-- Addition
result = 10 + 5 -- result is 15
-- Subtraction
result = 10 - 3 -- result is 7
-- Multiplication
result = 4 * 6 -- result is 24
-- Division
result = 15 / 3 -- result is 5Try it yourself
-- Create variables for item prices
-- TODO: Write your code here
-- Calculate total cost
-- TODO: Write your code here
-- Print the total cost
print(totalCost)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 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