2012-04-16 132 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"; 
} 

第一是首選。