ilya1725
ilya1725

Reputation: 4938

Tcl global variables in proc declaration

So I have this piece of Tcl code that inherited. Essentially it does the following:

set LOG_ALL     0
set LOG_DEBUG   1
set LOG_INFO    2
set LOG_WARN    3
set LOG_ERROR   4
set LOG_FATAL   5
set LOG_SILENT  6

proc v2 {vimm {log LOG_DEBUG}} {
    global LOG_DEBUG
    if {$log == $LOG_DEBUG} {
        puts "log"
    } else {
        puts "no log"
    }
}

I suspect that the original idea of the designed was to use global variable for the default value of the log parameter. However, it isn't working as expected and I can't find how to write it correctly, assuming it even possible.

Which syntax will be correct?

Thank you for help.

Upvotes: 3

Views: 8632

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

Well, this would be correct:

proc v2 [list vimm [list log $LOG_DEBUG]] {
    # ... body same as before
}

But that's just ugly. A neater way is:

proc v2 {vimm {log ""}} {  # Any dummy value would do...
    global LOG_DEBUG
    if {[llength [info level 0]] < 3} {
        set log $LOG_DEBUG
    }
    # ... as before
}

But the true Zen of Tcl is to not use numbers for this task at all, but rather names:

proc v2 {vimm {log "debug"}} {
    if {$log eq "debug"} {
        puts "log"
    } else {
        puts "no log"
    }
}

Upvotes: 5

Related Questions