i make a function like this
proc function1 {} {
set x 10
}
and i want to use x in second function like this
proc function2 {x} {
set y [expr x 10]
}
puts [function2 x]
invalid command name "x" this is the error i got
i tried to write puts [function2 function1.x]
and puts [function2 $x]
i got same error
like it can not read x from first function
how can i solve this error?
CodePudding user response:
The x
variable in function1
is local to it and is destroyed when the function returns. You can use
proc function1 {} {
global x
set x 10
}
to make it a global variable instead so that it can be seen by a later top-level puts [function2 x]
. Or use set ::x 10
to explicitly refer to the variable in the global namespace. Or use variable x
to bind it to the proc's namespace instead of the global one if they're different.
CodePudding user response:
Consider function1
which set x
and return the value of x
as well. In order to use that in function2
, you need to call:
puts [function2 [function1]]
By the way, function2
has a bug: You need $x
to get the value, not just x
.
proc function2 {x} {
set y [expr $x 10] ;# <--- $x, not x
}