Tuesday, August 12, 2008

ReDim

I have to admit that the way vbScript handles arrays is abysmal at best and hideous at worst. First of all, what is an array? It is a list. Pure and simple. vbScript expose things like multidimensional arrays, but that is just a list of lists. (or if there are three dimensions, a list of lists of lists).

OK let's declare an array


Dim arrFred(2)


So far so good. now some entries for the array.


arrFred(0) = 1
arrFred(1) = 54


OK so arrays use zero counting. That is the first element of an array is designated 0 and the last is length - 1. This is something to keep in mind as vbScript spends a lot of time flicking between 0 based and 1 based counting for various functions.

Now let's look at what the rant is really about. Say you want to make the list longer by one. Frequently done by people with say, shopping lists. Whoops forgot the eggs. I'll just write it on the end of the list. Lucky for us, there is the command


ReDim arrFred(3)
arrFred(2) = 42


So far so painless. Let's get back to calling that first value now we are at the shops and looking for the flour.


Wscript.Echo CStr(arrFred(0)) 'Outputs ""


That's right my chickadees, nothing. No output. And why? because when we did the ReDim. When you ReDim, your shopping list is torn up and thrown out. All values are returned to Null. Not very useful. So what options do we have? We could make the list impossibly long to begin with,


Dim arrFred(1000)


But my experience is that even if we make this really big, some user puts in more things than can really be dealt with by a really big number. I had a problem with a script that was designed to deal with around 20 servers. Someone then adapted my script to deal with 150 servers. If I had have used the really big number thought, then there would have been a failure there, as "really big" would have been 100 due to other constraints. So where is the answer? vbScript gives us the command


ReDim Preserve arrFred(arrFred.Length + 1)


This grows the array and keeps it's contents intact. Although why Preserve is not presumed for all arrays is quite beyond me and one of the dumbest things I have found in vbScript. If I ruled the world the code would be along the lines of.


arrFred.ClearAll
ReDim arrFred(3)


But I'm not. So I'll just highlight the issue.