Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBScript: How to utiliize a dictionary object returned from a function?

Tags:

vbscript

I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary.

Here is the relevant part of my function:

Function GetSomeStuff()
  '
  ' Get a recordset...
  '

  Dim stuff
  Set stuff = CreateObject("Scripting.Dictionary")
  rs.MoveFirst
  Do Until rs.EOF
    stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value
    rs.MoveNext
  Loop

  GetSomeStuff = stuff
End Function

How do I call this function and use the returned dictionary?

EDIT: I've tried this:

Dim someStuff
someStuff = GetSomeStuff

and

Dim someStuff
Set someStuff = GetSomeStuff

When I try to access someStuff, I get an error:

Microsoft VBScript runtime error: Object required: 'GetSomeStuff'

EDIT 2: Trying this in the function:

Set GetSomeStuff = stuff

Results in this error:

Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment.
like image 609
aphoria Avatar asked Sep 26 '08 14:09

aphoria


2 Answers

I wasn't too sure of what was your problem, so I experimented a bit.

It appears that you just missed that to assign a reference to an object, you have to use set, even for a return value:

Function GetSomeStuff
  Dim stuff
  Set stuff = CreateObject("Scripting.Dictionary")
    stuff.Add "A", "Anaconda"
    stuff.Add "B", "Boa"
    stuff.Add "C", "Cobra"

  Set GetSomeStuff = stuff
End Function

Set d = GetSomeStuff
Wscript.Echo d.Item("A")
Wscript.Echo d.Exists("B")
items = d.Items
For i = 0 To UBound(items)
  Wscript.Echo items(i)
Next
like image 61
PhiLho Avatar answered Oct 16 '22 12:10

PhiLho


Have you tried doing
set GetSomeStuff = stuff
in the last line of the function?

like image 35
tloach Avatar answered Oct 16 '22 10:10

tloach