Recent changes RSS feed

 

Bitlash Conditionals: if, while, and switch

In Bitlash you use while and if commands to control and repeat execution.

Bear in mind that as soon as the test condition for an if or while command fails, the execution of the command ends.

while expr: stmt1; stmt2; ...; stmtN

The while command repeats execution of the rest of the command line as long as the test expression is true.

> while millis() < 100000: d13=!d13

Execution of the while loop is blocking. In other words, during the execution of a while command, no other macros can run, since Bitlash is working as hard as it can to get to the end of that command line. The combination of while 1 with delay() is particularly deadly, since it uses the whole processor:

> print "this works but NOTE it will hog the whole arduino"
> while 1: print millis(); delay(1000)
(no prompt again until you press ^C)

Bitlash polls the serial port for Control-C during while loops, so you can break out.


if expr: stmt1; stmt2;... stmtN

The if command executes the rest of the command line if the test expression is true (nonzero); otherwise, execution stops.

> if d4: print "the light is on"

There is no else construct in Bitlash.


switch expr: macro0,macro1,...,macroN

The switch command selects one of N macros to run based on the value of a numeric expression. This provides a very easy way to build state machines, among other things.

Syntax:

switch selection-expression: macroid0,macroid1,macroid2,...,macroidN;

Note carefully the commas separating the macro specifiers. If you accidentally put semicolons there instead, you will have an interesting debugging experience.

The expression is evaluated to produce an integer result, which is used to select one of the supplied macro identifiers. The selected macro is called, then execution continues after the switch statement.

If the value of the selection expression is less than zero it is treated as zero and therefore the first supplied macro id is run. If the value is greater than N, the last macro id is run.

Example: This switch statement calls one macro from the list [up,down,left,right], depending on the value of d:

switch d:up,down,left,right;

If the value of d is ⇐ 0, the “up” macro will be called. The down macro is called for d==1, the left macro for d==2, and right will be called for d>=3.


Nesting

Nested conditionals work as you would expect:

> a=0;while a++<2: b=0;while b++<2: print a,b
1 1
1 2
2 1
2 2
>  

How to simulate a "for" loop

The simplest way is to unroll it as a while. Here is an example that initializes pins 3 through 8 as outputs and sets them to HIGH:

> i=3; while i<=8: pinmode(i,1); dw(i,1); i++

For extra credit, let's initialize the even ones on and the odd ones off:

> i=3; while i<=8: pinmode(i,1); dw(i,(i&1)); i++
 
conditionals.txt · Last modified: 2010/01/12 12:43 by wikiops