Re: (newbie) calling a proc with a varying number of arguments
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.tcl archive

Re: (newbie) calling a proc with a varying number of arguments

From: <slebetman@yahoo.com>
Date: Thu Dec 22 2005 - 03:17:55 CET

just80n@gmail.com wrote:
> hi all!
>
> I have a proc like this :
>
> proc doStuff {arg} {
> domystuff (puts, and lots of things)
> }
>
>
> the thing is:
>
> doStuff can be called like this
>
> doStuff onlyOneArg
>
> or like this:
>
> doStuff OneArg AnotherArg
>
> or like this:
>
> doStuff OneArg AnotherArg OhMyGodAThirdArg
>
> and I don't have any power over it
>
> How can I not get
> called "doStuff" with too many arguments error
>
> and pack all args into only one ?

Other people have already provided the correct answer of using args as
the last parameter in your proc. But Tcl also supports another
mechanism allowing variable arguments: default values.

Try the following:

  proc doStuff {arg1 {arg2 "hello"} args} {
    puts "arg1 = $arg1"
    puts "arg2 = $arg2"
    puts "args = $args"
  }

  doStuff
  wrong # args: should be "doStuff arg1 ?arg2? args"

  doStuff OneArg
  arg1 = OneArg
  arg2 = hello
  args =

  doStuff OneArg AnotherArg
  arg1 = OneArg
  arg2 = AnotherArg
  args =

  doStuff OneArg AnotherArg OhMyGodAThirdArg
  arg1 = OneArg
  arg2 = AnotherArg
  args = OhMyGodAThirdArg

  doStuff OneArg AnotherArg OhMyGodAThirdArg FourthArg "and arg 5"
  arg1 = OneArg
  arg2 = AnotherArg
  args = OhMyGodAThirdArg FourthArg {and arg 5}

As others have stated, the args parameter will return all remaining
arguments as a list. So it's easy to use all the list commands to
process (lindex, foreach etc..).
Received on Fri Dec 23 19:02:53 2005