Variables

A variable is a named memory location in which you can store a value like a number. There are four types of variables: number, string, boolean, and color. You must declare a variable type when you create one, and you can't change it later. For example, to use as a counter you can "increment a variable named loopCount inside a loop that repeats 4 times. When loopCount = 4, set the LED to red. You can retrieve this value anywhere in your program using the variable's name. Any code that takes a value can take your named variable instead.


Number Variables


5 number set

5 number


Below are a few basic techniques to use variables, but you are not limited to these.

Defining Variables

  1. When text programming, use the var keyword to define a new variable.
  2. The variable name must begin with either a letter or an underscore, and can contain letters, digits, and the _ character.
  3. Upper and lowercase letters are distinct because Javascript is case-sensitive.
  4. A variable declared outside of any function is global. It can be accessed from the main loop or from any function defined afterward. For simplicity, it can be helpful to define variables before the main loop, as we have done in the examples below.
  5. Use the = operator to assign a value to your variable. You can do this anywhere in your code, including the point at which you define the variable.
  6. More than one variable can be defined on a line using comma separation, or they can be defined on many lines using semicolon separation, like this:
// Global variables -- can be used anywhere in your program
var time = 3.55, var repeat = 6.1;
var predict = 2;

async function startProgram() {
    var localValue = -7; // This variable can only be used inside the startProgram function.
    
    // code
}

Using Variables

To use the value stored in your variable, you must 'reference' the variable in your code. To do this, just write the name of your variable anywhere you want to use its value.

For example, to make your robot change colors after a collision:

var color = {r:0, g:255, b:0};

async function changeColor() {
    color = {r:255, g:0, b:0};
};

registerEvent(EventType.onCollision, changeColor);

async function startProgram() {
    while (true) {
        setMainLed(color);
        await delay(0.1);
    }
};

Variables as Counters

It's useful to set a variable value in the main loop to use as a counter based on a condition. For example, let's extend the collision program to say the number of collisions, using var numCollisions:

var color = {r:0, g:255, b:0};
var numCollisions = 0;
var report = false;

async function changeColor() {
    color = {r:255, g:0, b:0};
    
    // Increase the number of collisions by 1 and
    // tell the main loop to report the result.
    ++numCollisions;
    report = true;
};

registerEvent(EventType.onCollision, changeColor);

async function startProgram() {
    while (true) {
        setMainLed(color);
        
        if (report) {
            // A new collision occurred. Tell the user.
            speak("" + numCollisions);
            delay(1);
            color = {r:0, g:255, b:0};
            report = false;
        }
        
        await delay(0.1);
    }
};

Comparing Variables

You can also compare two variable values to create conditional logic. Let's extend the color change program one last time. We'll make it exit when the user has reached a certain number of collisions:

var color = {r:0, g:255, b:0};
var numCollisions = 0;
var report = false;
const MAX_COLLISIONS = 3;  // <-- new variable

async function changeColor() {
    color = {r:255, g:0, b:0};
    
    // Increase the number of collisions by 1 and
    // tell the main loop to report the result.
    ++numCollisions;
    report = true;
};

registerEvent(EventType.onCollision, changeColor);

async function startProgram() {
    while (true) {
        setMainLed(color);
        
        if (report) {
            // A new collision occurred. Tell the user.
            speak("" + numCollisions);
            delay(1);
            color = {r:0, g:255, b:0};
            report = false;
            
            // Check to see if we have reached the max number of collisions.
            if (numCollisions === MAX_COLLISIONS) {
                speak("All done!");
                await delay(1.5);
                exitProgram();
            }
        }
        
        await delay(0.1);
    }
}

Sensors Reading

A sensor is very similar to a number variable, except it has a predefined context of a hardware sensor, like the gyroscope. You can read out the real-time value of a sensor by using it just like a variable in the speak command. For example, to read out the real-time velocity while accelerating use:

var speed = 20;

async function startProgram() {
	await speak("Velocity in centimeters per second", true);
	for (var _i1 = 0; _i1 < 4; _i1++) {
		setSpeed(speed);
		await delay(1);
		await speak(buildString("", Math.round(Math.sqrt((getVelocity().x ** 2) + (getVelocity().y ** 2)))), true);
		speed = (speed + 20);
	}
	stopRoll();
}

String Variables


5 string set

5 string

A string variable is a text string value. These are very useful for naming the players in a game, determining outcomes, or speaking any dynamic text. Often they are concatenated in a speak command, like in the Pythagorean Theorem program. A simple use of this is a program could be used speak the turn of a player in the game using:

var playerName = "";

async function startProgram() {
	playerName = "Bill";
	await speak(buildString("It's your turn", playerName), true);
}

Boolean Variables


5 boolean set

5 boolean

A boolean variable is a stored boolean value that can be assigned and operated on. Values can be true or false.


Color Variables


5 color set

5 color

A color variable is an RGB value that relates to a color which can be used to to dynamically read and set color values. You can also generate a human readable color string name from an RGB value for the below colors. The table will convert your RGB values to the closest one in the chart if it does not match exactly.

Visual Color Name RGB Values
Black r: 000, g: 000, b: 000
Dark Grey r: 060, g: 060, b: 060
Gray r: 100, g: 100, b: 100
Light Grey r: 200, g: 200, b: 200
Dark Blue r: 000, g: 000, b: 100
Blue r: 000, g: 000, b: 255
Light Blue r: 175, g: 175, b: 255
Cyan r: 000, g: 255, b: 255
Dark Purple r: 100, g: 000, b: 100
Purple r: 127, g:000, b: 255
Light Purple r: 255, g: 175, b: 255
Magenta r: 255, g: 000, b: 255
Dark Red r: 100, g: 000, b: 050
Red r: 255, g: 000, b: 000
Pink r: 255, g: 000, b: 127
Brown r: 100, g: 000, b: 000
Orange r: 255, g: 127, b: 000
Light Orange r: 255, g: 175, b: 175
Olive r: 100, g: 100, b: 000
Dark Green r: 000, g: 100, b: 000
Green r: 000, g: 255, b: 000
Light Green r: 175, g: 255, b: 175
Yellow r: 255, g: 255, b: 000
Light Yellow r: 255, g: 255, b: 175
White r: 255, g: 255, b: 255
--------------- ----------------------- ----------------

For example, you can use the color variable to create a program that changes the setMainLed to a random value after a spin, then speaks the color aloud:

var randomColor = {
	r: getRandomInt(0, 255),
	g: getRandomInt(0, 255),
	b: getRandomInt(0, 255)
};

async function startProgram() {
	while (true) {
		await rawMotor(4000, -4000, 0.25);
		randomColor = {
			r: getRandomInt(0, 255),
			g: getRandomInt(0, 255),
			b: getRandomInt(0, 255)
		};
		setMainLed(randomColor);
		await speak(buildString(randomColor), true);
		await delay(0.25);
		await delay(0.025);
	}
}