How to repeat in a function?

  • Hi guys, I am facing a problem and not sure if it's a bug... But whenever I run a repeat inside a function, the loopindex is always 0... How can I make this work?

    + System: On start of layout
    -> Functions: Call DoCount (Times: 100)
    
    * On function 'DoCount'
    * Parameter 'Times' (Number)
    ----+ System: Repeat Times times
    -----> System: Wait 0.1 × LoopIndex seconds
    -----> Text: Set text to LoopIndex
    

    The value of loopindex always says 0

  • It's not a bug. The loopindex after the wait is back to 0. You might try your luck with a function parameter, I believe I read somewhere that they are kept in a closure or something when used in conjunction with "wait" actions.

    + System: On start of layout
    -> Functions: Call DoCount (Times: 100, LocalLoopindex: 0)
    
    * On function 'DoCount'
    * Parameter 'Times' (Number)
    * Parameter 'LocalLoopindex' (Number)
    ----+ System: Repeat Times times
    -----> System: Set LocalLoopindex to LoopIndex
    -----> System: Wait 0.1 × LocalLoopindex seconds
    -----> Text: Set text to LocalLoopindex
    
  • The problem is by the time the "Wait" finishes, the loop has already finished, so the loopindex reverts back to 0.

    The new built-in functions can remember their parameters after a "Wait", but I don't think the previous example will work, because there is only one 'LocalLoopindex' variable which just gets overwritten. Instead try this:

    + System: On start of layout
    -> Functions: Call DoCount (Times: 100)
    
    * On function 'DoCount'
    * Parameter 'Times' (Number)
    ----+ System: Repeat Times times
    -----> Call DoRepeat (index: loopindex)
    
    * On function DoRepeat
    * Parameter 'index' (Number)
    -> System: Wait 0.1 × index seconds
    -> Text: Set text to index
    

    Since DoRepeat is called repeatedly, there are separate copies of the index variable which each remember their values after the wait, so it should work as intended.

    Or - just use an "Every" event or another different approach, this way is awkward...

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Thank you!

  • Ashley The weird part is that it actually did work, but not for the reason I thought. The variable was changed at 0.1 second interval so the "Set Text" action was setting the correct count.

    Absolutely need another function to create distinct scopes for independent variables.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)