Flow control
The following flow control structures are supported within Circuitscript.
if .. else
statement
An expression is evaluated and when it is true
, the block within the if
statement will be executed. Otherwise the block within the else
statement will be executed.
Multiple if .. else
can be defined to create a circuit graph based on different conditions.
Here is an example:
import lib
vcc = supply("VCC")
gnd = dgnd()
use_resistor = false
at vcc
wire down 100
branch:
wire right 200 down 100
if use_resistor:
add res(10k)
else:
add cap(100n)
wire down 100
to gnd
wire down 100
add res(10k)
wire down 100
to gnd
Loops
while
loop
An expression is evaluated and as long as it is true
, the block within the while
statement will be executed.
Here is an example:
import lib
vcc = supply("VCC")
gnd = dgnd()
at vcc
wire right 100
counter = 0
while counter < 5:
add led("yellow")
wire right 100
counter += 1
add res(10k)
wire right 100 down 100
to gnd
for .. in
loop
Loop through each item of an array, or list of values/objects.
Here is an example:
import lib
vcc = supply("VCC")
gnd = dgnd()
at vcc
wire right 100
# Loop through an array of colors
for i in ["yellow", "red", "blue", "green", "purple"]:
add led(i)
wire right 100
add res(10k)
wire right 100 down 100
to gnd
Interrupting flow control
break
When this is used within a loop (while
or for
), it will stop further execution of the loop.
Example:
import lib
vcc = supply("VCC")
gnd = dgnd()
at vcc
wire right 100
counter = 0
# Loop through an array of colors
while true:
add led("yellow")
wire right 100
counter += 1
# once this condition is reached, then stop the loop
if counter > 4:
break
add res(10k)
wire right 100 down 100
to gnd
break
within circuit paths
If break
is used within a branch
command, it will stop further execution within that branch
and return to the original branch
location.
continue
When this is used, it will jump to the next iteration of the loop. Unlike the break
keyword, this does not stop the loop completely.
import lib
vcc = supply("VCC")
gnd = dgnd()
at vcc
wire right 100
# Loop through an array of colors
for i in ["yellow", "red", "blue", "green", "purple"]:
# do not create red or green led!
if i == "red" || i == "green":
continue
add led(i)
wire right 100
add res(10k)
wire right 100 down 100
to gnd