1

I wrote a small program to help me learn how to work with arrays of objects in VBScript and I'm getting some results that don't quite make sense. I don't understand why the entire array is filled up with the last object entry when I go to print it out.

Class TestObj
    Public id
End Class

Dim arr()
Set tObj = new TestObj

Public Function fillArray()
    ReDim arr(10)

    For i = 0 To 9 Step 1
        Call createObj()
        Set arr(i) = tObj
    Next

    'Print the array in this function
    Print ("Printing from fillArray function")
    For i = 0 To 9 Step 1
        Print ("arr("&i&"):"& arr(i).id)
    Next

    Call printArray()
End Function

Public Function createObj()
   max = 100
   min = 1
   Randomize
   randInt = (int((max-min+1)*Rnd+min))
   Print ("Random Integer is: " &randInt)
   tObj.id = randInt
End Function


Public Function printArray()
    size = UBound(arr)
    Print ("Printing from printArray function")

    For i = 0 To size-1 Step 1
        Print ("arr("&i&"):"& arr(i).id)
    Next
End Function


Call fillArray()

Output is as follows:

Random Integer is: 80
Random Integer is: 92
Random Integer is: 70
Random Integer is: 10
Random Integer is: 18
Random Integer is: 100
Random Integer is: 27
Random Integer is: 47
Random Integer is: 34
Random Integer is: 60
Printing from fillArray function
arr(0):60
arr(1):60
arr(2):60
arr(3):60
arr(4):60
arr(5):60
arr(6):60
arr(7):60
arr(8):60
arr(9):60
Printing from printArray function
arr(0):60
arr(1):60
arr(2):60
arr(3):60
arr(4):60
arr(5):60
arr(6):60
arr(7):60
arr(8):60
arr(9):60

So as we can see, the last object was created with a id of 60 and some how every index of the array now contains that object.

1 Answer 1

5

You have exactly one tObj that gets Id numbers assigned successively. When you start to print, this tObj holds the last Id.

If you want (to learn about) arrays of objects (without atrocities like globals, Call, Dim x(), or mis/not-understandíngs of array size/UBound) then look at

Option Explicit

Class cX
  Public mnId
  Public Function ctor(nId)
    Set ctor = Me
    ctor.mnId = nId
  End Function
End Class

Sub printArrayofX(a)
  Dim i
  For i = 0 To UBound(a)
      Wscript.Echo a(i).mnId
  Next
End Sub

ReDim a(3)
Dim i
For i = 0 To UBound(a)
    Set a(i) = New cX.ctor(i)
Next

printArrayofX a

output:

cscript 39151577-2.vbs
0
1
2
3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.