Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Values dont survive functions??? 1

Status
Not open for further replies.

MoleDirect

Technical User
Sep 4, 2007
45
US
ok... here is an example..

I have a script that is something like this:

Code:
call main

function main

a = 1

msgbox ("A = " & a) ' and this would show A = 1

call nextone

function nextone
msgbox ("A = " & a) ' now, this shows A = 
end function        ' with A no longer having a value.

is there any way to prevent this?
 
It has to do with scope. You aren't declaring your variable 'a' with a Dim statement, so it ends up implicitly declared with a scope inside 'main' only. It doesn't exist outside that routine.

One way to avoid the problem is to pass 'a' as a parameter into the nextone routine. (I changed from functions to subs since you're not returning a value in your pseudocode example)

Code:
main

Sub main()
   Dim a
   a = 1
   msgbox ("A = " & a)
   nextone a
End Sub

Sub nextone(a)
   msgbox ("A = " & a)
End Sub

Another way is to explicitly declare 'a' with global scope like shown below.
Code:
Dim a
main

Sub main()
   a = 1
   msgbox ("A = " & a)
   nextone
End Sub

Sub nextone()
   msgbox ("A = " & a)
end Sub
 
You should try to use the first method guitarzan showed you as it can save you from other possible problems when declaring global variables.

--------------------------------------------------------------------------------
dm4ever
My philosophy: K.I.S.S - Keep It Simple Stupid
 
Yes, thanks for that dm4ever, I meant to add that caveat but forgot to...
 
Thank you all.. I will add this to my code!! Much appreciated! :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top