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

3

10

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?

Apothecary answered 23/6, 2011 at 9:53 Comment(0)
S
14

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!

Scarabaeoid answered 23/6, 2011 at 10:13 Comment(0)
R
11

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.

Robins answered 23/6, 2011 at 10:37 Comment(3)
+1 for checking the number of arguments provided, vs just checking to see if output was the empty string! Well, you'd get a +1 for the useful answer regardless, but I am glad you did it that way :)Numerology
Excellent answer, but watch out that in this way you cannot discriminate between a user giving the command 'log hello ""' and 'log hello'. You can change the default output string (changing "") but then you get a similar issue with the new value. May not happens often but when it happens...Proudman
@Roalt: Did you mean to put that comment on the other answer? With mine, you can distinguish by simply counting how many values were actually supplied. It's that easy.Robins
I
2

Another way to do this:

proc log {message {output ""}} {
    if {$output eq ""} {
        set output $::output
    }
}
Incrust answered 13/2, 2014 at 9:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.