Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

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

st: RE: AW: Macro dissapears after forval or foreach

From   "Nick Cox" <>
To   <>
Subject   st: RE: AW: Macro dissapears after forval or foreach
Date   Thu, 25 Feb 2010 16:52:07 -0000

Stefan's good question remains unanswered. It's true that the index of a -forval- or -foreach- loop disappears when the loop ends. 

The rationale for ending it is, presumably, that its rationale has ended. 

I would agree with any suggestion that this should be (better) documented, as on the face of it this feature is an exception to the general rules about locals, or at least an extra detail not obviously explicit.  

In practice, at least in my experience, it is rare that one has any use for the index outside the loop, so this feature has not (often?) been flagged before. 

The general implication -- for the exceptions to that -- is that one must save a copy within the loop, as was presumably clear to Stefan. Something like Martin's procedure would often work except that 

1. it would often require more effort to get at the last of any list

2. the -continue, break- command could be used to exit legally from a loop prematurely, and that would need separate attention. 

So, in general, copy any loop index you want later within the loop and just before you exit. 


Martin Weiss

You can put the list of values into a -local- beforehand, though, and this -local- will stick around:

local mynumbers 0 1

foreach x of local mynumbers{	
	di "value: `x'"

token `mynumbers'
di `1' " " `2'

If Stata did make it through the loop, the max of these values must be the endpoint, i.e. the value that was last assumed by `x'...

I'm just curious why running macros in forval or foreach 
disappear after the loop has finished.


foreach x in 0 1 {	
di "value: `x'"
di "value: `x'"

Following Stata 11 help for foreach and forvalues, 
both commands set local macros to given values.
According to the manual locals are available 
during the execution of the program or do-file 
unless they are deleted or overwritten.
So it should be there, shouldn't it? 

With dynamic value lists or "continue" there is some 
sense in preserving the last processed value.


Yes, I know workarounds... ;-))

*   For searches and help try:

© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index