Have you ever needed to run the same piece of code over and over with one variable changing? Yeah probably not. But if you ever need to, here’s how you do it!
What you need: A trigger and a property device
Step 1: Get the devices ready
This is probably the easiest step.
- Create a property device. This will be what keeps track of how many times the code has looped. Set the property type to “Number” and the starting value to 0. (This may not be necessary depending on the conditional statement you choose. If you want it to be more like a while loop rather than a for loop, this might not be needed)
- Create a trigger device. Set “Trigger when receiving on” to a channel name. I used “loop code” Also, there might need to be a delay so that all the code can run fast enough, or it is just necessary in your situation
Step 2: Create a condition
Now create a block in the trigger. First we need a condition to check whether the code should keep looping, or stop. Make sure it has an “else” statement. I just checked to see if the property we made was less than 10.
Step 3: If the condition passes
When the conditional statement passes, it will do something, then loop the code. To loop the code, just call the channel that sends a signal on this same trigger.
This code I have here adds 1 to the property, and transmits on the channel called barrier #. (The # means whatever the property is. It’ll make sense later.) Then it calls the channel to run the trigger again.
Step 4: If the condition fails
This just means the condition has been met, and the looping needs to stop. So, nothing needs to be here! There are some things that may need to be here though depending on the situation. For example, if you want something to happen when all the looping has finished, you could transmit on a channel like this:
Step 5: Do whatever else you need to do
This loop can be used in many different situations, so I can’t put anything specific here. But I can show what I did!
I just made 9 barriers with numbers on them that are not visible on start.
The barrier with a one on it activates when receiving on “barrier 1”. The barrier with a two on it activates when receiving on “barrier 2”. and so on and so forth. (This is why I had the transmit on channel barrier # before. Told ya it would make sense!)
When the button at the top is pressed it transmits on the channel “loop code” This starts the loop and goes through each number and transmits on its corresponding channel. When all the looping is finished, it makes text appear that says “All done!”
This was my first guide made on the forums, so let me know if this made sense and/or was helpful!