Announcement

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

  • Nesting foreach loops within a while loop

    I am trying to create a foreach loop within a while loop, and the issue is that the foreach loop executes completely, even if the condition to break the while loop has been met using one of the variables. I'm including source code to explain what is happening.

    I want the while loop to stop after the `loop_e' > `total_e' the first time it happens (when the foreach loop loops over trunk). However, the while loop only stops executing after all the variables in the foreach loop have been looped over.

    Code:
    sysuse auto, clear
    local total_e = 1e-2 
    local loop_e = 1 
    
    while `loop_e' > `total_e' {
        foreach var in trunk weight length turn {
            di "`var'"
            local loop_e = 1e-6 
        }
    }

  • #2
    This does not really lend itself to nested loops, at least not in Stata. (I can think of a way to do it in Stata with nested loops, but it's pretty convoluted and opaque--I wouldn't go there.)

    This will work instead:
    Code:
    sysuse auto, clear
    local total_e = 1e-2
    local loop_e = 1
    
    foreach var in trunk weight length turn {
        di "`var'"
        local loop_e = 1e-6
        if `loop_e' <= `total_e' continue, break
    }
    Note: It is normally against my computing "religion" to us the syntax of an -if- command where the guarded command appears on the same line, rather than putting curly braces around it. But given that, in this case, the guarded command's sole purpose is to break entirely out of the loop, it seems relatively safe to do: there is no other command that could sensibly be added to the construct after -continue, break-.

    Comment

    Working...
    X