Re: Accessing variable defined in one proc, in another proc



On 11 jun, 09:35, rick <vagabond_maver...@xxxxxxxxx> wrote:
I am defining a variable inside a proc. And I want to use this
variable in another proc.
One way is to return that variable form that proc to the main script
and then access it in another proc by using global command. But is
there any way , I can access it in another proc directly.

eg :

proc1 {

set a xxx

}

proc2 {

puts $a

}

main script :

proc1
proc2

In the above example I want a defined in proc 1 to be accessible in
proc 2.

Variables defined and used in a procedure exist only while that
procedure is being run. When the procedure returns all variables
within that procedure are gone.

What you really want is a global variable:

proc proc1 {
global a
set a 1
}
proc proc2 {
global a
puts $a
}

# Main code

proc1
proc2

You can look at the "variable" command too that defines
variables in other namespaces than the global namespace.

What you can also do is use the upvar command, if proc1
uses proc2:

proc proc1 {
set a 1
proc2
puts "After proc2: $a"
}

proc proc2
upvar 1 a use_a
puts "From proc1: $use_a"
set use_a 2
}

That works because the variable "a" as defined in proc1 still
exists when proc2 is running - proc1 is also still there
(albeit nothing happens until proc2 returns).

Regards,

Arjen




.



Relevant Pages

  • waiting for input of widget and return input value
    ... run proc1, then proc1 will invoke proc2 and popup some checkbutton for ... to invoke proc3, proc3 will check which button was checked and return a ... checked variable list, then proc2 return the list to proc1, and proc1 ... proc proc1 { ...
    (comp.lang.tcl)
  • Re: Accessing variable defined in one proc, in another proc
    ... One way is to return that variable form that proc to the main script ... One approach is to assign to a global variable in proc1, ... reference it in proc2. ... can make it a namespace variable and put both procs within the same ...
    (comp.lang.tcl)
  • Re: Accessing variable defined in one proc, in another proc
    ... One way is to return that variable form that proc to the main script ... One approach is to assign to a global variable in proc1, ... reference it in proc2. ... can make it a namespace variable and put both procs within the same ...
    (comp.lang.tcl)
  • finding process and waiting for it to end
    ... I am working on a jscript that launches a process (proc1). ... Proc1 launches a secondary process (proc2) and then exits. ... I want my script to launch proc1 and then find the process associated ...
    (microsoft.public.scripting.jscript)
  • Re: Gracefully stopping an infinite loop after a particular keyboard input
    ... But by "ctrl+c" the script stops at that very ... fconfigure stdin -buffering no -blocking no ... proc do_stuff { ... set service ...
    (comp.lang.tcl)