Local variables are created "on the fly" while a function is being executed. They are only known to the function that creates them. For example, the following code contains an error:
Now = Time() ; Record the time in local variable Now
WaitUntil(30.0) ; Wait for 30 seconds
Elapsed = Time()-Now ; Calculate elapsed time (ERROR!)
until (Elapsed > RequestElapsed)
The error is a consequence of the variable Now being a local variable in function ExplainDelay. Now is only known while the interpreter is executing function ExplainDelay. The variable Now in function WaitUntil is a different variable known only to function WaitUntil. WaitUntil's Now is not the same as ExplainDelay's Now!
Local variables can appear anywhere in a function. They do not have to be predeclared as in Pascal. They are created when they are first referenced (usually by writing to the variable). Take the example above written (correctly) as one function.
Now = Time() ; Record current time in Now
Elapsed = Time()-Now ; Calculate elapsed time in Elapsed
until (Elapsed > 30.0)
The variable Now is created in line 2 and the variable Elapsed is created in line 4. Explain has the advantage of not requiring a list of data declarations before the action of a function begins. There is a price to pay, however. Consider the incorrect function below:
Now = Time()
while (Elapsed>30.0) ; Test for elapsed time passed (ERROR!)
Elapsed = Time()-Now
In this example, the variable Elapsed is read before it is set! Explain™ just creates the variable, Elapsed and give it a special value of NIL. The Explain compiler does not complain about this syntax. The interpreter, however, complains that you are trying to compare a NIL value to a REAL value.
There is another problem with local variables. When you leave the function where they are declared, their values disappear! You cannot permanently store a value in a local variable. For example, consider the following incorrect code:
if (NewValue ne NIL)
RepRate = NewValue
RepRate = RepRate+1 ; ERROR!
while (RunExperiment() eq 0) ; return of zero = experiment was ok
SetSpeed(NIL) ; go faster by incrementing RepRate
... ; continue after loop
The problem is that local variable RepRate doesn't live past the return statement in function SetSpeed. The first time SetSpeed is called using parameter 1, RepRate is set correctly. However, by the time SetSpeed is called with value NIL, the original RepRate has disappeared and the new RepRate has an incorrect value.