vbscript - can a variable set in a Function be made global?

Status
Not open for further replies.

Aeirould

Ars Tribunus Angusticlavius
7,535
Subscriptor
Functions should be self-contained. Always.

Of course, if you *do* insist on breaking the rules, just Dim the variable outside of any sub or function and it is global.

Code:
Dim x<P>Function y(a)
    x = a ^ 2
    y = x ^ 2
End Function<P>Function z(b)
    z = x ^ b
End Function

But I repeat, this is *really really* bad!!!!

You can't control whether or not "x" in the above example has a valid value when you call z.

Better would be to define a function that calculates what you need to be able to do from both functions and call that function from both functions:
Code:
Function a(b)
    a = b ^ 2
End Function
Function y(c)
    y = a(c) ^ 2
End Function
Function z(d,e)
    z = a(d) ^ e
End Function

Of course, these are useless examples with bad naming, but they convey the point.
 

haji

Ars Tribunus Militum
1,515
wow! great reply, thanks. That was exactly what I was looking for.
I dont mean to be breaking the rules but since I am learning all this on the fly, I ma not always sure what the rules are. I wanted to do it because it looked very nice and neat, basically... and it would be very modular and easy to understand.
code:<HR>
Code:
Dim x
Dim y<P>FuncA
FuncB
FuncC
wscript.echo c
quit<P>Function FuncA
a = 4
End Function<P>Function FuncB
b = a - 1
End Function<P>Function FuncC
c = a - b

I see how this would get very messy if my scripts had a to scale up in size.

:)

//haji
 

Aeirould

Ars Tribunus Angusticlavius
7,535
Subscriptor
Ah, well, that's the problem...

You're using the term Function when you mean to use the term Sub or Procedure (in VBScript, it's Sub)

A Function is something that returns a value based on passed parameters, as the built in Sqr() function does. If the above is an accurate reduction of what your code is doing, functions would be better than subs.

A Sub or Procedure is something that performs an action and does not return a value.
 
Status
Not open for further replies.