Search code examples
loopsvariablesscopepugeach

In Pug, how to use a variable outside (set for global use) the each loop it is created in?


Below, I'm trying to get the personRef variable inside (locally set scope) the pug each loop of person in persons to come out. That way on the following line PersObj which I need for each object loop it's a part of can use the personRef variable from the loop right above. Basically, I need the local scope in the loop to be set globally outside the loop.

each object in objects
   - var objNum = objects.indexOf(vehicle)+1
   - var personRef=person.object_ref
   each person in persons
     - var personNum = persons.indexOf(driver)+1
     if (some condition) && (object.person_ref == objNum)
       - var personRef=object.person_ref
       - break
     else if (condition)
       - var personRef= personNum
     else if (condition)
       - continue
   PersObj(id = "O"+objNum, PersonRef = "P"+personRef)

Solution

  • its hard to understand what exact behavoir you want to achieve but i will try. "- var personRef = something" defines a variable. you only need this once in your code. if you define it outside of a loop, you can also use it inside. if you have "- var personRef = something" again inside the loop, you "overwrite" it with a variable that can only be used within the loops scope. you can always reassign a variables value like this: "personRef = somethingElse" with out using the "- var".

    so it should probably look smth like this:

    each object in objects
     - var objNum = objects.indexOf(vehicle)+1
     - var personRef=person.object_ref // define the variable here
       each person in persons
         - var personNum = persons.indexOf(driver)+1
         if (some condition) && (object.person_ref == objNum)
           - personRef=object.person_ref // here you dont need var, because you only reassign a value
           - break
         else if (condition)
           - personRef= personNum // here as well
         else if (condition)
           - continue
       PersObj(id = "O"+objNum, PersonRef = "P"+personRef)
    

    besides that, i cant really tell what the code is supposed to do, can you please elaborate what that code is supposed to do. please also explain: what is "objects" what is "persons" what is "vehicle" what is "driver"