Saturday, November 19, 2011

VBScript Parentheses

VBScript Parentheses

Function SumOfElements(a)
    Dim x
    SumOfElements = 0
    If Not IsArray(a) Then Exit Function
    For x = LBOUND(a) To UBOUND(a)
     SumOfElements = SumOfElements + a(x)
End Function

Dim w(1000), x
for x = 0 To 1000
  w(x) = x

Wscript.Echo SumOfElements(w)

VbScript uses parentheses for three quite distinct purposes:

1. To indicate the order of evaluation within an expression
2. To enclose the list of arguments passed to a function
3. To enclose the list of array element indices

Because of the structure of the VBScript language, the meaning of the parentheses is never ambiguous. However, it is sometimes confusing to figure out what each set of parentheses mean. In the invocation of the preceding SumOfElement function, the array w is passed as an argument. The parentheses around the argument w are present because function arguments are always enclosed in parentheses. Therefore, the argument that is passed to the SumOfElements function is simply w, which is a variable. Following the normal rules for argument passing, this means that the array is passed by reference. To Pass the array by value, enclose it in an additional set of parentheses, as follows:

Wscript.Echo SumOfElements((w))

Here, the outermost parentheses are still the parentheses used to enclose the argument list of the function. Within them, the (w) argument is now seen as an expression by VBScript, and so the argument is passed by value, not by reference.

The most extreme case can be illustrated as follows:
Wscript.Echo SumOfElements((w(1)))

This expression can be decoded as follows: The innermost set of parentheses specifies an element index for the array w, and so the result is a simple variable, w(1). the next set of parentheses encloses the variable as before, making it an expression. The final, outermost, parentheses delimit the argument list of the function SumOfElements. [Source:Windows Script Host By Tim Hill]