A variable is a named box that remembers a value. You put something in it, read it back later, and change it whenever you need to. Almost every game is really just a pile of variables changing over time — a score, a position, a timer.
1. Make one with let
Write let, a name, =, and a starting value. Here score starts at 0, and we show it on screen:
let score = 0;
function draw() {
cls(1);
print('Score: ' + score, 8, 8, 7);
}The name score now stands for that value everywhere you use it.
2. Change it any time
That is the whole point of a variable — it can vary. Give it a new value with =, or build on the one it already has. Here the score climbs by 1 each time you press space:
let score = 0;
function update() {
if (keyp(' ')) {
score = score + 1; // take the old score, add 1, store it back
}
}
function draw() {
cls(1);
print('Score: ' + score, 8, 8, 7);
}score = score + 1 looks strange next to maths, but in code = means "put the right side into the left". So it reads: the new score is the old score plus one. You will write this constantly.
3. Values come in types
So far score held a number. But a variable can hold other kinds of value too, called types. The main ones you will meet:
- Number —
0,7,3.5. Scores, positions, timers. - String — text like
Spark, written in quotes. Names, messages. - Boolean —
trueorfalse. Yes/no facts, like "is the game over?" - Object — a bundle of related values grouped together.
- Array — a list of many values.
Each type gets its own lesson next — this one is just the big idea: a name that holds a value you can change.
What you learned
- A variable is a named box that remembers a value.
let name = valuemakes one;name = newValuechanges it.score = score + 1stores a new value built from the old one.- Values have types — number, string, boolean, object, array — each covered next.