Loops
Why write something 10 times when you can write it once?
Before you start
Okay, you're going to need to know the syntax for the for loop.
- Read the w3schools javascript for-loop guide.
Start the script
Start the script normally. Lets get a protocol to work with too.
/**
* Advanced Scripting 1 - Loops
*
* Demonstrates the ability of javascript loops to simplify code, and make
* advanced behaviours feasable.
*
* made: 2017-03-23
* by: William A. Norman
*/
// Takes a single image with red lights.
var protocol = new CameraProtocol("example_protocol")
protocol.setAnalysisID ("example")
protocol.setNumberLoops ( 1 )
protocol.setFramesPerLoop ([ 1 ])
protocol.setMeasuringLight ([ 1 ])
protocol.setSaturationFlash ([ 0 ])
protocol.setExposure ([ "50us" ])
protocol.setFrameInterval ([ "70ms" ])
// Set starting conditions
set_intensity(0)
// Take a sample imageset
run_protocol(protocol)
Create a for loop
Okay, for this example we want to run a simple 30 second day, 10 times. But we don't want to write the same code over and over, so lets create a loop.
for (int i = 0; i < 10; i++) {
}
Anything we put in that loop will be executed once for every i
.
What are we waiting for: Lets make it do something! Place this code between the following:
wait("10s")
set_intensity(100)
wait("10s")
run_protocol(protocol)
wait("10s")
set_intensity(0)
Run that script. You should get an experiment with 10 days (not including day_-1!).
Using loop variables
It runs 10 times.. but we want it to increase the lighting every day. Well, we can use i
(Which stands for iterator) as a variable within the loop. Lets replace the loop contents with this:
wait("10s")
set_intensity(i*10)
wait("10s")
run_protocol(protocol)
wait("10s")
set_intensity(0)
Complete script
Okay, your script should look like this:
/**
* Advanced Scripting 1 - Loops
*
* Demonstrates the ability of javascript loops to simplify code, and make
* advanced behaviours feasable.
*
* made: 2017-03-23
* by: William A. Norman
*/
// Takes a single image with red lights.
var protocol = new CameraProtocol("example_protocol")
protocol.setAnalysisID ("example")
protocol.setNumberLoops ( 1 )
protocol.setFramesPerLoop ([ 1 ])
protocol.setMeasuringLight ([ 1 ])
protocol.setSaturationFlash ([ 0 ])
protocol.setExposure ([ "50us" ])
protocol.setFrameInterval ([ "70ms" ])
// Set starting conditions
set_intensity(0)
// Take a sample imageset
run_protocol(protocol)
for (int i = 0; i < 10; i++) {
wait("10s")
set_intensity(i*10)
wait("10s")
run_protocol(protocol)
wait("10s")
set_intensity(0)
}
Nice!