Higune
Higune

Reputation: 653

VBScript get custom object from array

I have some problems with an array in VBScript: I have a central array, in this I save some custom objects. Later on, I want access these elements to print out the objects. But this don't work. Here is my code;

sub start
    redim selektionsArray(0)
    for i = 0 to 10
            Dim TheDude : Set TheDude = (New Selektion2)("a" & i, "b" & i)

            ReDim Preserve selektionsArray(ubound(selektionsArray) + 1)
            set selektionsArray(ubound(selektionsArray)) = TheDude
            'Works
            msgbox selektionsArray(ubound(selektionsArray)).Typ & " = " & selektionsArray(ubound(selektionsArray)).Wert
    next 

    dim i
    for i = 0 to ubound(selektionsArray)
        set element3 = selektionsArray(i)
        'don't work
        msgbox selektionsArray(i).Typ & " = " & selektionsArray(i).Wert
    next

    dim sel
    for each sel in selektionsArray
        'don't work to
        msgbox sel.Wert
    next

    'strange thing is ubound(selektionsArray) --> 11

end sub

Class Selektion2
     Private m_typ
     Private m_wert

     Public Default Function Init(Typ, Wert)
         m_typ = Typ
         m_wert = Wert

         Set Init = Me
     End Function

     Public Property Get Typ 
         Typ = m_typ
     End Property

     Public Property Get Wert
         Wert = m_wert
     End Property

     public function getWert()
        getWert = m_wert
     end function
 End Class

I don't can access the array-Elements outside the initialisation loop, what is here wrong?

Upvotes: 1

Views: 839

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Your error is to assume that

redim selektionsArray(0)

creates an empty array. It does not, the array has an empty first element at index 0. Adding further objects is no problem, but when you try to

set element3 = selektionsArray(i)

for i = 0, or to access the firs sel in the For Each loop, that empty element can't be use to Set the/a variable. So change the 'create my array' statement to

redim selektionsArray(-1)

Upvotes: 1

Related Questions