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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

global variables in a sourced file not available in main

Status
Not open for further replies.

jaytco

Vendor
Dec 13, 2001
88
US
I have created a source file with multiple procedures. The source file declares global variables within the procedure. When my main program sources the source file and executes one of the procedures, the global variable in that sourced procedure does not appear to be global to the main program. Is this just a syntax issue, or am I unable to declare a global variable in a sourced file?

example) source.exp #source file
proc procCftStart { } {
global procCftStatus
global procCftSpawnId
global procCftPid

set procCftStatus 1
send_user "procCftStat = $procCftStatus\n"
...
}

example) main.exp #main program
source ./source.exp
...
procCftStart # Call procedure in source.exp
if { $procCftStatus != 1 } { # program dies here
send_user "ERROR: Shell Failure - $Cft\n"
exit
}

error)
procCftStatus = 1 #Sent by procedure called by main
can't read "procCftStatus": no such variable # Error sent by main when trying to read global variable.
 
You can declare/set a global variable in a sourced script.

sourced.tcl:
Code:
global myvar
set myvar 1

main.tcl
Code:
  source sourced.tcl
  puts $myvar

tclsh main.tcl
->1

I think that the error you got didn't come from where you think.
Maybe you refered the global inside a proc without declaring it global?

HTH

ulis
 
I found that I had to declare the variable global in each procedure that it was used it. Initially I just declared it global when I set the value. --Thx Jay
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top