Variable scope in VBScript functions
I have a question about variable s开发者_高级运维cope in VBScript. I know there's the following keywords (from autoitscript.com):
- Dim = Local scope if the variable name doesn't already exist globally (in which case it reuses the global variable!)
- Global = Forces creation of the variable in the Global scope
- Local = Forces creation of the variable in the Local/Function scope
Imagine that I have the following .vbs file:
Dim strPath
strPath = "C:\folder"
DisplayPath strPath
Sub DisplayPath(strPath) 'Does this strPath get it's own local scope?
MsgBox strPath
End Sub
In the function: DisplayPath(strPath)
, is strPath
a local variable? Or do functions/subs have access to the strPath
defined at the top of the main section of the script as a global variable?
Also, what's the point of explicitly using Dim
versus just defining variables as I use them, which is possible in scripting languages?
The strPath
in the DisplayPath
procedure will be a new variable but not for the reasons you expect, there is subtle problem with your code that will cloud the issue.
When calling Sub
procedure the VBScript syntax does not include parentheses. For example:-
Sub MyProc(Param1, Param2)
'' # Do stuff
End Sub
MyProc("Hello", "World")
the above would result in a syntax error. It should be called:-
MyProc "Hello", "World"
Now when there is only one parameter a syntax error does not occur. This is because another use of parentheses is as part of an expression e.g. '(a + b) * c'. In the case of:-
DisplayPath(strPath)
VBScript resolves the "expression" (strPath)
and pass the result to DisplayPath
. Its this result that gives rise to new storage hold the result the expression.
Had you called with
DisplayPath strPath
no new created.
However what about this:-
Sub DisplayPath(something)
MsgBox something
End Sub
There is still no new storage allocated. something
will point at the same memory that strPath
does.
Edit
The code below works:-
Dim strPath
strPath = "c:\folder"
Display
Sub Display()
MsgBox strPath
End Sub
The declaration of strPath
outside of a procedure causes it to have global scope.
As to the point of using explicit Dim
what would happen if the assignment line above looked like this?
strPath = "c:\folder"
A new variable called strPath
would come into existence and strPath
would remain empty. You should always begin your VBScript files with the line:-
Option Explicit
This will force you to explicitly Dim
all variables to be used and will save you hours of debugging time.
精彩评论