Learn

The “compute” part of “computer” means we cannot leave what computers do best out of this lesson! We can compute new values for our variables with arithmetic operators.

This is useful when we work with values that need to be numerically changed. Let’s take a look at this in action:

player1Score = 0 player1Score = player1Score + 1 print(player1Score) --output: 1

The syntax may look a bit strange at first. Let’s break it down. Recall that = means you’re assigning what is on the right of = to the variable on its left. To understand this, we need to evaluate the expression on the right first (player1Score + 1), then reassign it back to the left variable (player1Score).

  • On the right is player1Score + 1
  • We first access the value of player1Score that is currently at 0
  • Replace player1Score with its current value and we get 0 + 1 which equals 1
  • Then, the = assigns the new value back into player1Score
  • Now, player1Score will have a new value of 1

If we were to add the same line of code again with the newly updated value, what do you think it will be?

player1Score = player1Score + 1 print(player1Score)

Since player1Score starts out with 1 from the previous calculation, adding 1 to the variable means 1 + 1. player1Score will now have the number 2!

Other arithmetic operators work with variables too — see the example below and also Lua’s documentation:

Operator Example
Addition myVariable = myVariable + 1
Subtraction myVariable = myVariable - 1
Multiplication myVariable = myVariable * 1
Division myVariable = myVariable / 1
Exponentiation myVariable = myVariable ^ 1
Remainder myVariable = myVariable % 1
Negation myVariable = -myVariable

Instructions

1.

In our game, Kamala scores one point!

Add 1 to the player1Score variable and use print() to output the modified player1Score.

2.

Foul! Bruno loses 2 points.

Subtract 2 from the player2Score variable and use print() to output the modified player2Score

3.

C-C-Combo! Bruno gets a point multiplier, multiply the player2Score variable by 1.5 and use print() to output the modified player2Score.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?