Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Macro expansion in a while loop

    I'm having a little trouble with macro expansion inside a while loop. As a toy example, the following code gives me an error message:

    Code:
    set obs 10
    local i = 1
    local xx noisily
    while `i' < 5 {
      cap `xx' {
          gen a`i' = runiform() in 1/9
      }
      local i = `i' + 1  
    }

    Here's the error message I get with Stata 15.1:
    Code:
    . set obs 10
    number of observations (_N) was 0, now 10
    
    . local i = 1
    
    . local xx noisily
    
    . while `i' < 5 {
      2.   cap `xx' {
      3.       gen a`i' = runiform() in 1/9
      4.   }
      5.   local i = `i' + 1  
      6. }
    (1 missing value generated)
    (1 missing value generated)
    (1 missing value generated)
    (1 missing value generated)
    } is not a valid command name
    r(199);
    For what it's worth, the same code runs fine without the macro:

    Code:
    set obs 10
    local i = 1
    while `i' < 5 {
      cap noisily {
          gen a`i' = runiform() in 1/9
      }
      local i = `i' + 1  
    }
    Has anyone run into this issue, or something like it, before? If so, what is incorrect with my code? Or is this a Stata bug?

    Thanks!
    Last edited by kkranker; 07 Feb 2019, 13:34.

  • #2
    Very strange. I can replicate the problem on my setup as well.

    I also note that if instead of using -while- to control the loop we do
    Code:
    clear
    set obs 10
    local i = 1
    local xx noisily
    forvalues i = 1/4 {
        cap `xx' {
            gen a`i' = runiform() in 1/9
        }
    }
    there is no error generated. And no error if I replace the -forvalues- with a -foreach i of numlist- loop.

    So I think this is a Stata bug. You might want to send this to Tech Support.

    Comment


    • #3
      There was a similar discussion previously, see the logic in #9.

      https://www.statalist.org/forums/for...preted-wrongly

      Comment


      • #4
        Very interesting. Thank you, Andrew, for pointing up the prior discussion.

        Comment


        • #5
          Thanks Andrew for pointing out the old discussion. (I had looked at old forums but obviously didn't use the right search terms.) I still find this behavior odd and unexpected, and I wonder why this doesn't come up more often and why it can't be fixed. But I guess Stata knows about this and it's the intended behavior.

          Comment


          • #6
            This issue is reported to Tech Support with reference to this discussion.

            Comment

            Working...
            X