PDA

View Full Version : variable from a for in loop


tg_spline
02-03-2010, 06:00 PM
Can anybody tell me how can i make a variable from this for-in loop's values?


int $index[] = {0,1,2,3,4};
string $face;


for ($face in $index) {
print("pPlane1.f[" + ($face + "]") + "\n");
};

I want a string array with these values.

pPlane1.f[0]
pPlane1.f[1]
pPlane1.f[2]
pPlane1.f[3]
pPlane1.f[4]

Thanks!

jaydru
02-04-2010, 12:10 AM
just need to cast it into a variable that has been declared outside of the for loop

string $return[] = {};
for ( $i=0; $i<5; $i++ )
$return[size($return)] = ("pPlane1.f[" + $i + "]");


james.

outoftune
02-04-2010, 08:08 AM
this is a good example when NOT to use a for in loop.

btw I think its never a good idea. If you want to come back at some point and add something useful to it you will end up doing a regular for loop anyway. set up abbreviations for the for-loop in your IDE and be done

oh, and what James said :)

ewerybody
02-04-2010, 09:20 AM
Ok word! There is absolutely NO need to browse an array like {0,1,2,3,4} in a for-in-loop! :D Its actually a quite good mel-joke.

But I have to disagree: The for-in-loop is very useful!
Writing $variable[$i] all the time is much more work and less clean than $obj for instance.

Furthermore you can do stuff like:for ($obj in `ls -sl`)
...and the `ls -sl` will only be evaluated ONCE! (But note that the thing will break if the command does not return anything. Other than if you pass an empty array!)

Whereas infor($i = 0; $i < size(`ls -sl`); $i++)
...size(`ls -sl`) would be evaluated EACH loop.

however: Of course size is no heavy option. But If you need a count-variable anyways I tend to use the following thing:{
int $index[] = {0,1,2,3,4};
string $faces[];
int $numFaces;

for ($face in $index)
$faces[$numFaces++] = "pPlane1.f[" + $face + "]";

print $faces;
print("$numFaces: " + $numFaces + "\n");
}

No offense james: But asking for the size each loop and having $i with always the same value is very funny as well ;] :beer:

tg_spline
02-04-2010, 05:18 PM
The values at $index[] (0,1,2,3,4) are only sample numbers. i will use the script with other, not continuous numbers. But your replies was helpfull. Now i can correct my code.

Thanks!

Robert Bateman
02-05-2010, 01:47 PM
btw I think its never a good idea.

For-in loops are far more efficient than for loops.Therefore, when applicable, always prefer for-in.

NaughtyNathan
02-05-2010, 02:27 PM
btw I think its never a good idea.

the fact that python ONLY supports this kind of for-loop is probably a good indication that it is always a good idea. :D ;)

:nathaN

CGTalk Moderation
02-05-2010, 02:27 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.