user707549
user707549

Reputation:

about the global variable in tcl

I have a question about global variable in TCL:

set gvar "abc"

proc justTest {} {
    global gvar
    puts $global
}

if a variable is declared in global space, we should use global keyword to access the global variable inside a proc, but if where is no global variable is declared, but we use global keyword inside a function, what will happen? for example:

no global variable is declared

proc justTest {} {
        global gvar
        set here $gvar
        puts $here
    }

then what will happen?

Upvotes: 0

Views: 8887

Answers (2)

Hai Vu
Hai Vu

Reputation: 40733

Case 1: you are referencing the global variable

In this case, you are using its value, but not setting it. You don't have to set the global variable gvar before defining your proc. You only need to set gvar before calling your proc. Failure to set gvar before hand will cause error.

Case 2: you set the value of the global variable

In this case, you don't need to create the global variable before calling your proc. After calling your proc, the global variable will be created and available.

Upvotes: 2

Andrew Cheong
Andrew Cheong

Reputation: 30273

Same as if you tried to access a local variable that was never declared.

can't read "gvar": no such variable

On a related note, if you set the variable from within the proc, you would be able to access it from the main scope (after calling the proc of course).

Upvotes: 2

Related Questions