Execute! III

Okay, last time, I left you with two functions which were nearly identical. This one:

Const pi = 3.1416
r = 0
WScript.Echo Main()
Function Main()
 r = 2.5
 Dim result
 Dim str
 str = “result=pi*(r*r)”
 Execute str
 Main = result
End Function

This function returns a nonzero value. Although r has a value of zero in the global scope, function Main() also declares r and assigns a nonzero value. The local version of r overrides the global r within the function; because the expression is being executed within the function, r hs a value and the result is nonzero. I also gave you a near-twin:

Const pi = 3.1416
r = 0
WScript.Echo Main()
Function Main()
 r = 2.5
 Dim result
 Dim str
 str = “result=pi*(r*r)”
 ExecuteGlobal str
 Main = result
End Function

In this case, the mathematical expression is being executed in the global scope, which essentially means it’s being raised up out of the function. In the global scope, r has a value of zero, so the result of the expression is zero. There’s another problem, too: When the expression executes globally, the variable result is implicitly declared in the global scope. That variable was declared explicitly within the function, though, so the function’s version of “result” is different from the global scope’s version of “result.” That means the local version of “result” is never being assigned a value within the local scope, so the function will always return a zero value.

This little series serves to illustrate several important truths about scope in VBScript:

First, globally-declared variables are accessible everywhere.

Second, locally-declared variables (within a function or sub) or only available within their local scope.

Third, a locally-declared variable will, within a local scope, have precedence over a globally-declared variable of the same name.

Fourth, Option Explicit is your friend :).

Fifth, although you may run ExecuteGlobal within a local scope, whatever code you’re executing executes within the global scope, not the local scope.