views:

456

answers:

3

Hello

I'm fairly new to vbscript and I'm struggling a little as I'm more familiar with Javascript. Can someone please give me a hand?

Does vbscript allow the use of named array keys like I have in my example below?

For example I have:

Dim result(3)
result(age)       = 60
result(firstname) = "Tony"
result(height)    = 187
result(weight)    = 76

msgbox("Age: "    & result(age)       & vbCr &_
       "Name: "   & result(firstname) & vbCr &_
       "Height: " & result(height)    & vbCr &_
       "Weight: " & result(weight)    )

The resulting msgbox shows:

  Age: 76 
  Name: 76 
  Height: 76 
  Weight: 76

This seems to assign every element in the result array to 76, which should only be assigned to the "weight" element.

Is this happening because vbscript only accepts integers as the key/ index for arrays?

Any help is greatly appreciated.

Thanks Turgs

A: 

No VBScript only allows for an integer index. That being said you could declare integer constants to deliver the functionality you're wanting.

If you want a named array (like the example above) then you'll probably need some kind of dictionary.

Kane
+4  A: 

In order to acheive this you need to use a Dictionary object from the Scripting library:-

Dim result : Set result = CreateObject("Scripting.Dictionary")
result.Add "Age", 60
result.Add "Name", "Tony"

and so on. You can retrieve items as:-

DIm age : age = result("Age")

However if you have fixed set of identifiers you might consider defining a class:-

Class CResult
    Public Age
    Public Name
End Class

Dim result : Set result = new CResult
result.Age = 60
result.Name = "Tony"

MsgBox "Age: "    & result.Age       & vbCrLf & _
   "Name: "   & result.Nname) & vbCrLf

BTW Typically we use CR LF for new lines not just CR and also note if you are using method or function as statement (as in the MsgBox above) don't enclose parameters in ( ).

AnthonyWJones
+1  A: 

Hello

In addition to Andrew's solution on this page, I've been able to use the Dictionary object in VBScript to do what I was after using a syntax more like Associative Arrays normall use in other languages:

Dim result 
Set result = CreateObject("scripting.dictionary") 

result("age") = 60 
result("firstname") = "Tony" 
result("height") = 187 
result("weight") = 76 

msgbox("Age: "       & result("age")       & vbCr &_ 
      "First Name: " & result("firstname") & vbCr &_ 
      "Height: "     & result("height")    & vbCr &_ 
      "Weight: "     & result("weight")    )

More information on the dictionary object can be found here: http://www.microsoft.com/technet/scriptcenter/guide/sas_scr_ildk.mspx

I hope that's helpful to others trying to do the same thing.

Thanks to Richard Mueller for providing this solution via the microsoft.public.scripting.vbscript Usenet group.

Cheers

Turgs

Turgs