Question

Seems like a basic question but I cannot find the answer anywhere :-S

I am puzzled by the experiment below:

Tcl 8.5.13 interactive shell
% set args [list 1 2 3]
1 2 3
% llength $args
3
% set argv $args
1 2 3
% llength $argv
3
% set argv ${args}
1 2 3
% llength $argv
3

So far so good, but then:

% proc test { args } { set argv ${args}; set argc [llength $argv]; return $argc}
% test $args
1

Looks like the list becomes a strings during argument passing. Can someone explain what's going on here ??

The only workaround I found so far is this one:

% proc test2 { argsName } { upvar 1 $argsName args; set argv ${args}; set argc [llength $argv]; return $argc}
% test2 args
3

Any other suggestion ?

Was it helpful?

Solution

Your problem is the argument name args which has a special meaning.

From the manual of proc:

If the last formal argument has the name args, then a call to the procedure may contain more actual arguments than the procedure has formal arguments. In this case, all of the actual arguments starting at the one that would be assigned to args are combined into a list (as if the list command had been used); this combined value is assigned to the local variable args.

So if you use any other name for the argument, it will work fine.


Example use for args:

proc putargs args {
    puts $args
}

# Call with more than one argument
putargs foo bar
# Use as command prefix for callbacks.
trace add execution glob {enter leave} {list putargs GLOB}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top