如何在proc之外访问变量 [英] How do I access a variable outside of a proc
问题描述
我正在尝试围绕Tcl变量作用域,但是我一直坚持我认为这是一个简单的概念:如何访问在proc之外定义的变量,但是我没有明确传递给proc?
I'm trying to wrap my head around Tcl variable scopes, but I'm stuck on what I thought would be a simple concept: how can I access a variable that I've defined outside of my proc, but that I do not explicitly pass to the proc?
我试图避免设置一堆全局变量,而只访问我在特定名称空间中定义的变量.我需要在下面的代码中添加些什么,以便proc可以访问变量 a
,而该变量显然不在proc的范围内?
I'm trying to avoid setting a bunch of global variables, and only access variables that I define within a particular namespace. What do I need to add to my code below so that the proc can access the variable a
, which is obviously not in the scope of the proc?
set a apples
proc myList {b c} {
puts [concat $a $b $c]
}
推荐答案
您可以使用 upvar
:
You can use upvar
:
set a apples
proc myList {b c} {
upvar a a
puts [concat $a $b $c]
}
或者,稍微扩展一下示例以显示"source"变量不必在全局范围内存在:
Or, expanding the example a bit to show the "source" variable does not have to exist in the global scope:
proc p1 {} { set a 10; p2 }
proc p2 {} { upvar 1 a b; puts "in p2, value is $b" }
p1
输出
in p2, value is 10
If a
was defined in a namespace, you can use variable
:
namespace eval foo {
set a apples
# OR
# variable a apples
}
proc foo::myList {b c} {
variable a
puts [concat $a $b $c]
}
或者如果 a
是在全局范围内创建的,您仍然可以使用 ::
来访问它而无需 global
函数(我ll参考关于此问题的问题):
Or if a
was created in the global scope, you can still access it without the global
function, using ::
(I'll reference this SO question for this one):
proc myList {b c} {
puts [concat $::a $b $c]
}
这篇关于如何在proc之外访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!