Variables and Constants

In the last section we looked at a few examples of variables and applied them into our hello world example. But what if you want to store a value and ensure it cannot be altered? For that, you would need a constant.

A constant is declared and initialized in much the same way as a variable, but is preceded by the keyword, const. For example:

const float total = 95.1;

Here we have a float type constant named “total” with a value of 95.1. Once initialized, the value of total cannot be modified and attempts to assign a new value to the constant will be met with an error message in the build window.

The variables Section

Typically, a variable or constant is only visible in the block in which it is defined. If our constant, total, were to be declared in an on start event hook, the constant would only be visible within that event hook. The variables section allows the user to declare variables and constants that may need to be visible globally across the t script. So if multiple parts of our script need to reference our constant, total, we can initialize it in the variables section to ensure it is accessible. A simple example of a variables section can be seen below.

variables {
     const float total = 95.1;
     CanMessage msg;
}

Environment Variables

Where variables defined in the variables section are visible across the entire t script, environment variables, meaning variables defined in the envvar section, are visible across the entire environment. This includes other t scripts as well as user applications on a connected host computer via CANlib.

envvar {
     CanMessage msg;
     int rpm;
}

Where to Declare?

As in other C-like languages, variables and constants can be defined anywhere, not just at the beginning of a block or within the variables section. However, they should be declared before attempting to use them. The example below demonstrates an error where the variable, bitrate, is being initialized before being declared.

bitrate = 500;
int bitrate;

Conversely, variables can be declared in scopes as small as within the parameters of a for loop. For example, in this for loop we have declared and initialized the int “counter” with a value of 3. We go on to finish declaring the conditions that the for loop will use to determine whether it should continue or end the loop. The counter variable will only exist within the for loop and not be visible beyond.

for (int counter = 3; counter > 0; counter--) {
      …..
}
Lesson tags: t script, TRX

Variables and Constants Quiz

Please sign up for the course before taking this quiz.
  1. 1. True or false, a variable should be initialized before it is declared.

  2. 2. The value of a constant can be changed by:

Back to: <em>t</em> Scripting > Basics of t