Quote:
Originally Posted by DustyPorViva
Why do:
for (temp.i = 3; i > 0; i --) {
sleep(1);
}
instead of just doing sleep(3)?
|
You're right, I
did mean to add a count-down, but I wasn't thinking.
Quote:
Originally Posted by Jiroxys7
Isn't the for (temp.i = 3; i > 0; i --) {} thing an array? (correct me if i'm wrong but i think thats what its called)
|
It's called a
for loop.
Quote:
I've seen these alot. and apparently it can be very useful in certain script.
Could someone explain how this works? Its always seemed very confusing to me. reading how "for" works in the offline editor helps a little, but what's it checking? and what exactly is that script doing?
i would guess it's checking if temp.i = 3. or is it setting it to 3? then telling it it's greater than 0 then subtracting 1?
or, by looking at Dusty's comment, is it producing three one second sleeps?
then once temp.i == 0, it tells it to stop telling it to sleep.. or something?
and where's it pulling the initial value for temp.i from anyway?
|
Let's say you have something like
PHP Code:
for (temp.i = 0; i < 10; i ++) {
echo(i);
sleep(1);
}
It's going to output this in RC, with a one second delay between each number.
What it does is loop through something a certain number of times.
PHP Code:
function countTo(number, delay) {
for (temp.i = 0; i < number; i ++) {
echo(i);
sleep(delay);
}
}
would let you count to any number.
PHP Code:
temp.v = 0;
for (temp.n = 0; n < 5; n ++) {
v += int(random(1, 5));
sleep(0.5);
}
Here's what this would be doing in English.
Quote:
SET v TO 0
START FOR LOOP
SET n TO 0
SET v to 2
SLEEP .5 SECONDS
SET n TO 1
SET v to 3
SLEEP .5 SECONDS
SET n to 2
SET v to 6
SLEEP .5 SECONDS
[and all the way to 4]
|
Here's the basic structure.
PHP Code:
for (variable = start; variable (inequality) max/min; variable change) {
// code to be executed
}
so
PHP Code:
for (temp.x = 3; x > 0; x --) {
echo(x);
}
would say that x starts at 3. It would then execute the code in the middle by outputting '3'. Then, x is decreased to 2. It checks if 2 is more than 0, which it is, so it keeps going and executes the code. x now equals 1, which is more than 0, so it goes again. x now equals 0, which is not more than 0, so it breaks out of the for loop.
Another, different type of
for loop is like a
foreach loop in other languages. It's done like this:
PHP Code:
for (variable : array) {
echo(variable);
}
Arrays are defined like this
PHP Code:
temp.array = {"one", "two", "three", "hello", "world"};
which means you can also do
PHP Code:
for (variable : {"one", "two", "three", "hello", "world"}) {
echo(variable);
}
however, you need to specify a variable
PHP Code:
for (temp.number : array) {
echo(number);
}
would output
Quote:
one
two
three
hello
world
|
Be sure not to get the two types of for loops mixed up. The
for each loop does the same thing as
PHP Code:
temp.array = {"one", "two", "three", "hello", "world"};
for (temp.i = 0; i < array.size(); i ++) {
temp.variable = array[i];
}
heh, long post