Dynamic array in vbscript gets cleared when control comes out of loop
Asked Answered
N

1

1

I am newbie to VBScript. I am trying my hands at Dynamic array concept in VBScript below is my code. Code:

dim arr()
For i = 0 To 3
    Redim arr(i+1,2)
    arr(i,0)=i
    arr(i,1)=i+1
    MsgBox arr(i,0)&"-"&arr(i,1)
Next
For i = 0 To UBound(arr)
    MsgBox arr(i,0)&" "&arr(i,1)
Next

As soon as the control comes into second loop all the values stored in arr are lost. i do not understand why and how? I've tried adding Preserve keyword but it throws subscript out of range error. TIA!!!

Nanci answered 8/4, 2015 at 16:46 Comment(0)
B
1

[oops, missed the two dimensions] Use ReDim Preserve instead of plain ReDim. (And get rid of the () in the Dim statement.) [/oops]

You can only grow dynamic arrays (not fixed arrays Dimmed with (n[,m,..])). A more dimensional array can only grow the last dimension (docs). So:

Option Explicit

ReDim arr(1, -1) ' <-- dynamic
Dim i
For i = 0 To 3
    ReDim Preserve arr(1, i) ' last dim grows
    arr(0, i) = i
    arr(1, i) = i + 1
Next
For i = 0 To 3
    WScript.Echo i & ":", arr(0, i), arr(1, i)
Next

output:

cscript 29520636.vbs
0 0 1
1 1 2
2 2 3
3 3 4
Buxtehude answered 8/4, 2015 at 16:52 Comment(6)
removing () gives me error like Type Mismatch and i've already tried with Preserve keyword..it throws Subscript out of range errorNanci
did u try my above code in some .vbs file and ran at your end?Nanci
so you are saying we can grow only horizontally (columns) and not vertically (rows) ?Nanci
@MrunalGosar - just read the docs: msdn.microsoft.com/en-us/librarY/c850dt17%28v=vs.84%29.aspxBuxtehude
thnx.. man..but it is quite strange that in the above code it works perfectly fine in the first loop but as soon as the control comes out of the loop it fails..quite weirdNanci
@MrunalGosar - that's because a ReDim without Preserve does not preserve the data (i.e. zaps the array).Buxtehude

© 2022 - 2024 — McMap. All rights reserved.