VBScript variable loses its content?
I have the following code. What it does is that it reads all key , vlaues from a properties开发者_C百科 file.
Function readProperties(fileName) Dim oFS : Set oFS = CreateObject( "Scripting.FileSystemObject" ) Dim dicProps : Set dicProps = CreateObject( "Scripting.Dictionary" ) Dim oTS : Set oTS = oFS.OpenTextFile( fileName ) Do Until oTS.AtEndOfStream Dim sLine : sLine = Trim( oTS.ReadLine ) 'Wscript.Echo sLine If "" sLine Then If not "#" = Left( sLine, 1 ) Then Dim aParts : aParts = Split( sLine, "=" ) If 1 UBound( aParts ) Then WScript.Echo oTS.Line, "bad property line", sLine Else 'Wscript.Echo "Adding: " & aParts( 0 ) &" => " & aParts( 1 ) dicProps( Trim( aParts( 0 ) ) ) = Trim( aParts( 1 ) ) 'WScript.Echo oTS.Line, "good property line", sLine End If End If End If Loop oTS.Close 'readProperties = dicProps Dim sKey For Each sKey In dicProps.Keys WScript.Echo sKey, "=>", dicProps( sKey ) Next End Function
The weird thing is that if I assign the value of dicProps
to readProperties
, the code does not work anymore.
Am I missing something in this?
Use
Set readProperties = dicProps
You alway have to use Set when working with objects.
(Not enough points to comment, so posting as an answer instead)
Let me try to summarize the correct but a bit messy answers from above:
- When working with objects, the preferred syntax is
Set objVar2 = objVar1
, whereas scalars are assigned withVar2 = Var1
. BASIC dialects dropped the once required Let (Let Var2 = Var1
) for variable value assignment. When returning a value from a method (Function), the syntax is
FunctionName = Result
, following the rules of variable type assignment, i.e.Function MyObject() ' Assign an object as the return value Set MyObject = Result End Function
Function MyScalar() ' Assign a scalar as the return value MyScalar = Result End Function
精彩评论