2012-04-16 101 views
4

我有一个下面的代码:如何声明全局变量其中仅使用在PROC

proc testList {setupFile ""} { 
    if {$setupFile == ""} { 
    set setupFile location 
    } 
} 
proc run {} { 
    puts "$setupFile" 
} 

我正在语法错误。我知道如果我声明proc中的setupFile变量,即在主proc然后我可以追加它与命名空间说:: 65WL :: setupFile使其全局但不知道如何做到这一点,如果一个变量本身定义在proc只要。

回答

4

对于特定过程运行不是本地的Tcl变量需要绑定到命名空间;命名空间可以是全局命名空间(有一个特殊的命令),但不需要。因此,有是两个程序之间共享的变量,你需要给它暴露名:现在

proc testList {{setup_file ""}} { 
    # Use the 'eq' operator; more efficient for string equality 
    if {$setup_file eq ""} { 
    set setup_file location 
    } 
    global setupFile 
    set setupFile $setup_file 
} 
proc run {} { 
    global setupFile 
    puts "$setupFile" 
} 

,这就是分享一个完整的变量。如果您只想分享价值,还有其他一些选择。例如,这两种可能性:

proc testList {{setup_file ""}} { 
    if {$setup_file eq ""} { 
    set setup_file location 
    } 
    # Create a procedure body at run-time 
    proc run {} [concat [list set setupFile $setup_file] \; { 
    puts "$setupFile" 
    }] 
} 
proc testList {{setup_file ""}} { 
    if {$setup_file eq ""} { 
    set setup_file location 
    } 
    # Set the value through combined use of aliases and a lambda term 
    interp alias {} run {} apply {setupFile { 
    puts "$setupFile" 
    }} $setup_file 
} 

没有与Tcl的8.6更多的选择,但仍处于测试阶段。

8

您可以使用::来引用全局命名空间。

proc testList {{local_setupFile location}} { 
    # the default value is set in the arguments list. 
    set ::setupFile $local_setupFile 
} 

proc run {} { 
    puts $::setupFile 
} 
0

可以使用uplevel,upvar和/或全球

proc testList {{setupFile ""}} { 
    if {$setupFile eq ""} { 
    set setupFile location; 
    uplevel set setupFile $setupFile; 
    } 
} 
proc run {} { 
    upvar setupFile setupFile; 
    puts "$setupFile"; 
} 

proc run {} { 
    global setupFile; 
    puts "$setupFile"; 
} 

第一是首选。