Notice: On March 31, it was **announced** that Statalist is moving from an email list to a **forum**. The old list will shut down at the end of May, and its replacement, **statalist.org** is already up and running.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

From |
Nick Cox <njcoxstata@gmail.com> |

To |
statalist@hsphsun2.harvard.edu |

Subject |
Re: st: passing indefinite no of arguments |

Date |
Sat, 31 Mar 2012 00:48:50 +0100 |

di `: list sizeof 0 ' Nick On Fri, Mar 30, 2012 at 8:52 PM, Maarten Buis <maartenlbuis@gmail.com> wrote: > On Fri, Mar 30, 2012 at 8:43 PM, tashi lama wrote: >> So, say I have a do file which will add the arguments and display >> >> *sum >> >> args a b c d >> >> di `a' +`b'+`c'+`d' >> >> This one is easy since I could pass 4 arguments a, b, c and d and my do file will sum them. What if I don't know the no of arguments I am passing? I could have passed 2, 3, 5 or even 1 and find their sum. > > Here is a quick solution. The logic is that within a program a number > of locals are created. The local `0' contains all arguments, and the > local `1' contains the first argument, `2' the second, etc. This is > not very stable, e.g. when you call -tokenize- the locals `1', `2' > etc. will be replaced, but in a small program like the one below it is > an easy enough solution. > > *---------- begin example ------------ > program drop _all > program define sumargs > // count the number of arguments > local k : word count `0' > > // add them > tempname sum > scalar `sum' = 0 > forvalues i = 1/`k' { > scalar `sum' = `sum' + ``i'' > } > > // display the result > di `sum' > end > > sumargs 2 3 7 > sumargs 4 > sumargs 2 3 4 5 6 7 8 > *---------- end example ------------- > * * For searches and help try: * http://www.stata.com/help.cgi?search * http://www.stata.com/support/statalist/faq * http://www.ats.ucla.edu/stat/stata/

**Follow-Ups**:**RE: st: passing indefinite no of arguments***From:*tashi lama <ltashi32@hotmail.com>

**References**:**st: passing indefinite no of arguments***From:*tashi lama <ltashi32@hotmail.com>

**Re: st: passing indefinite no of arguments***From:*Maarten Buis <maartenlbuis@gmail.com>

- Prev by Date:
**st: Extracting confidence intervals from corrgram** - Next by Date:
**RE: st: Correcting Multicollinearity** - Previous by thread:
**Re: st: passing indefinite no of arguments** - Next by thread:
**RE: st: passing indefinite no of arguments** - Index(es):