Object References in VBScript (Variables and Values in VBScript, Part 3), Part 2By Bill Wilkinson
In Part 1 we looked at what, specifically, object references were and discussed their limitations on copying objects within VBScript. In this part we'll examine how VBScript handles copying arrays.
What About Arrays?
So we can't copy objects. Can we copy arrays? The answer may surprise you. Again, a small demonstration seems in order:
You really should copy that code to your own ASP page and try it out. And then try as many variations on it as you can think of! But since this is an article, we'll have to show you the output:
After copying ar1 to ar2: · ar1 = this array is unchanged · ar2 = this array is unchanged After changing ar2(1): · ar1 = this array is unchanged · ar2 = this second array is unchanged After alter by VAL of ar1: · ar1 = this array is unchanged · ar2 = this second array is unchanged After alter by REF of ar1: · ar1 = this array is CHANGED in alterArrayByRef! · ar2 = this second array is unchanged After alter by REF of ar2: · ar1 = this array is CHANGED in alterArrayByRef! · ar2 = this second array is CHANGED in alterArrayByRef!
Did you look very carefully at those results? Indeed, after the assignment of
the two arrays are the same. But then look: we change one of the elements of one of the arrays ... and the other
array remains unchanged! We don't need to go any further: Arrays are always copied! You can not have two
variables refer to the same array in VBScript! It just does not happen.
What About ByRef?
"But wait!" you exclaim, "I can see that when you call the
alterArrayByRef subroutine that changes to
the array inside the
Sub are reflected in the array outside the
Yes. True. And, if you want to think of it this way, this is the exception that proves the rule. But a better
way of looking at it, I think, is to say that anytime you are inside a
and are using a
ByRef parameter, you don't really have another variable ... you just have an "alias"
for the caller's variable. Without going into too many details, the way VBScript is written this is almost exactly
what is happening. It is interesting to note that Java only allows calling
ByVal (but then, it never
copies arrays!) and many C++ programmers have a hard time understanding when a call is truly
in that language.
Sometimes, one might hope for the seeming simplicity of Java, but trust me that the programmer can pay a price for
that simplicity. The lesson, if there is one? Be happy with what you have! And use
ByRef for most
object and array references and
ByVal for most primitive values passed to subroutines and functions.
A Last Word
Since we've gotten into a discussion of
ByVal, it is worth dragging up this
old article that warns of the dangers of putting parentheses into your
VBScript code when you don't need to!