Nasal Loops: Difference between revisions

Jump to navigation Jump to search
m
nothing much
m (nothing much)
Line 13: Line 13:
   )  
   )  
{
{
   
     # loop body
     # loop body
}
}
Line 20: Line 19:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
for(var i=0; i < 3; i = i+1) {
for (var i=0; i < 3; i = i+1) {
# loop body
    # loop body
}
}


while (condition) {
while (condition) {
# loop body
    # loop body
}
}
</syntaxhighlight>
</syntaxhighlight>


The differences are that there is no do{}while(); construct, and there is a foreach, which takes a local variable name as its first argument and a vector as its second:
The differences are that there is no <tt>do{}while()</tt>; construct, and there is a foreach/forindex, which takes a local variable name as its first argument and a vector as its second:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 35: Line 34:
</syntaxhighlight>
</syntaxhighlight>


In other words, even though foreach or forindex look like function calls, they work differently.
In other words, even though foreach or forindex look like function calls, they work differently and they have braces after the parentheses.


The hash/vector index expression is an lvalue that can be assigned as well as inspected:
The hash/vector index expression (one that uses brackets) is an lvalue that can be assigned as well as inspected:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 43: Line 42:
</syntaxhighlight>
</syntaxhighlight>


To walk through all elements of a hash, for a foreach loop on the keys of they hash. Then you call pull up the values of the hash using the key.  Example:
To walk through all elements of a hash, use a foreach loop on the keys of they hash. Then you call pull up the values of the hash using the key.  Example:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
myhash= {first: 1000, second: 250, third: 25.2 };
myhash = {first: 1000, second: 250, third: 25.2 };
foreach (var i; keys (myhash)) {
foreach (var i; keys (myhash)) {
   #multiply each value by 2:
   #multiply each value by 2:
Line 53: Line 52:
   print (i, ": ", myhash[i]);
   print (i, ": ", myhash[i]);
}
}
# this will print in some order:
#first: 2000
#second: 250
#thid: 25.2
</syntaxhighlight>
</syntaxhighlight>


There is also a "forindex", which is like foreach except that it assigns the index of each element, instead of the value, to the loop variable.
There is also a "forindex", which is like foreach except that it assigns the ''index'' of each element, instead of the value, to the loop variable.


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 64: Line 67:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
var c=0;
var c = 0;
while( c<5 )
while( c < 5 )
   print( c+=1 );
   print( c += 1 );
print("end of loop\n");
print("end of loop\n");
</syntaxhighlight>
</syntaxhighlight>
395

edits

Navigation menu