Constants in TCL

In most programming it is useful to avoid putting 'magic numbers' scattered around your script. For two main reasons: readability and maintenance. Replacing a number with a name can make the script easier for someone not immediately familiar with it to read and understand. A few weeks after you write your script, YOU are that someone! Also your objectives will probably evolve as the script develops so changes will be necessary. Although such numbers 'never' change, in reality they all-too-often do just that. So giving names to constants achieves both objectives: The name aids readability and declaring the value in a single place aids maintenance.

Constants in TCL are declared in the constants section of the script, and the syntax is extremely simple:

Constants:
        One=1, Two=2, Left=0, Right=1, maxTrains=8

Each name is given a value and each time that name appears in your script that value is used. In essence a constant is similar to a variable except you cannot change the value.

In addition to numeric constants you can use string constants:

Constants:
        LostTrainMessage="Current detect of train @t has been lost"
Actions:
WHEN ... DO Draw message (1,2,3)=LostTrainMessage

Note the use of an embedded variable in the constant string. When the string is displayed the "@t" will be replaced by the value of variable t which could be the number of the train that has been lost.

In addition to scalar variables (single variables) you can have constant arrays, and these can contain either numbers or strings, or even a mixture of both:

Constants:
        ca[]= [11,12,13,"hello"]

As a constant is in most respects the same as a variable (except you cannot change the value), you can set a value to point to a numeric constant. Incrementing the pointer will point to the next constant:

Constants:
        One=1, Two=2
Actions:
WHEN ... DO p=&one, draw message (1,1,1)=*p, p+=1, draw message (1,2,1)=*p
{ will display 1 and 2 being the numeric values of constant one and the one defined after it.

Last updated 20 Aug 2008

© Howard Amos 2005-2009