For loop in a script. Number of loops or using a input_boolean to exit loop. How to do it?

I have a script which flashes a group of lights 3 times but I would like to know how to make two differnet changes to the code (they would be different scripts)

  • flash x number of times
  • repeat untll an input_boolean (flashing_enabled) is false

current code is like this:


flash_lights_sub:
  sequence:
  - service: script.all_lights_on  
  - delay: 00:00:02
  - service: script.all_lights_off
  - delay: 00:00:02

flash_lights:
  alias: Flash House Lights 3 times
  sequence:
  ... do some init...  
  - service: script.flash_lights_sub
  - service: script.flash_lights_sub
  - service: script.flash_lights_sub  
  ... do some cleanup...

I tried the following but it didn’t work as it stated that the scripts was already running when it had done it’s first loop:
I assume this is because it doesn’t like recursion. Can a method be called asynchronously? Allowing the parent call to exit?

flash_lights_driver:
  sequence:
  - service: script.flash_lights_sub
  - service: script.flash_lights_condition
  
flash_lights_condition:
  sequence:
    - service_template: >
        {% if is_state("input_boolean.flashing_enabled", "on") %}
          script.flash_lights_driver
        {% else %}
          script.flash_lights_cleanup
        {% endif %}

flash_lights_cleanup:
  sequence:
  ... do some cleanup...
  
flash_lights:
  sequence:
  ... do some init...
- service: script.flash_lights_driver

How should I do this?

I was hoping that Jinja would have either a ‘while’ operator (to do a while input_boolean is true condition) or a ‘for’ operator which supports numbers (to allow for a for i = 1 to x style loop)
But I don’t think it does…

Repeat a group of actions

Perfect, thanks, I must have missed that page!

Let me know if you need help implementing it.

1 Like

Just got it all working, thanks for the offer of help :slight_smile:

1 Like