Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as default value of a TCL proc argument

I've got a variable that I would like to use as default value for an argument:

proc log {message {output $::output}} {
   ....
}

Is there a way to do this or need I to evaluate the variable inside my proc?

like image 965
patrick Avatar asked Jun 23 '11 09:06

patrick


3 Answers

Yes, but you cannot use curly braces ({}) for your argument list. You declare the procedure e.g. this way:

proc log [list message [list output $::output]] {
   ....
}

But be aware:
The variable is evaluated at the time when the procedure is declared, not when it is executed!

like image 166
bmk Avatar answered Oct 24 '22 00:10

bmk


If you want a default argument that is only defined in value at the time you call, you have to be more tricky. The key is that you can use info level 0 to get the list of arguments to the current procedure call, and then you just check the length of that list:

proc log {message {output ""}} {
    if {[llength [info level 0]] < 3} {
        set output $::output
    }
    ...
}

Remember, when checking the list of arguments, the first one is the name of the command itself.

like image 11
Donal Fellows Avatar answered Oct 24 '22 00:10

Donal Fellows


Another way to do this:

proc log {message {output ""}} {
    if {$output eq ""} {
        set output $::output
    }
}
like image 1
Daniel Garcia Alhama Avatar answered Oct 23 '22 23:10

Daniel Garcia Alhama