hugo
hugo

Reputation: 1

I can understand "global var" in Tcl, but what does "global $var" mean?

I'm a learner in Tcl language, I can't understand the use of global in this proc:

proc linkPeers { link } {
    global $link
    set entry [lsearch -inline [set $link] "nodes {*}"]
    return [lindex $entry 1]
} 

"global var" refers to an external, global variable named var.

"global $var" I can't understand, who can tell me?

Upvotes: 0

Views: 90

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137587

The code is a bit strange, and is actually buggy.

It should have been this instead (#0 in quotes for syntax highlighting reasons only):

proc linkPeers { link } {
    upvar "#0" $link items
    set entry [lsearch -inline $items "nodes {*}"]
    return [lindex $entry 1]
} 

The key is that the link argument is the name of a global variable, yet you want to access it as a local variable within the procedure. The global command does that, but the name is a variable so you have to use [set $link] to do the read afterwards. Switching to using upvar #0 instead of global lets us use a different, fixed name locally, and that makes it easier to use elsewhere.

The bug in the original code? The global variable had better not be called either link or entry!

Upvotes: 2

Related Questions