PDA

View Full Version : How do I declare variables as local? (WXP)



lhomme77
05-22-2002, 01:23 AM
I'm writing a script that uses an int i for a for loop. However, I also have a function which that loop calls that also uses an int i for a for loop. When the first loop calls the function (that contains the second "i" loop), withOUT passing the i value to that function, it comes back to the first loop and the first i value has incremented through the incrementing of the 2nd i value in the called function.

I hope that's not too confusing. Basically, I'm just wondering why the 2 i values aren't local to their functions and how I can make them such.

Thanks!

Steve

adamdelves
05-23-2002, 01:33 PM
There are two kinds of variables in script. Global and local.
Global variables are those which are alive through out script execution. They are declared in the main part of the script outside functions and sub routines.
Local variables are declared inside a procedures (functions or subroutines). When the procedure has finished the variable is destroyed.

If the same gloabl variable is used inside function as a local variable, it can produce strange results. To keep track of variables use the Option Explicit command at the top of your script. This doesn't only help you keep track of where and when all the variables are declared but also helps to ensure variables aren't miss spelt.
You must declare each variable individually using the Dim method before you use them. Here's an example:
<pre>
Option Explicit

Dim glabalVar1
Dim glabalVar2
Dim globalVar3

&lt;&lt;-CODE-&gt;&gt;
Sub
Dim localVar1
Dim localVar2
Dim localVar3

&lt;&lt;-CODE--&gt;
End Sub
</pre>

lhomme77
05-24-2002, 02:43 AM
So by saying Option Explicit at the top, what effect does that have exactly on those global variables that you declare below?

adamdelves
05-24-2002, 08:29 AM
Option Explicit has no effect what so ever on the variables. Option Explicit ensures that all variables used in the script are declared using the Dim statement, any variables not decalred will cause an error to be raised.
This may seem a bit time consuming but in large scripts misspelling a variable can cause very strange results and even errors. Option explicit prevents this by making sure you have declared all variables.