PDA

View Full Version : Creating a function for a for-loop


Mathieson
06-17-2007, 05:02 PM
I am using the exact same for loop over and over again through my script, but with a different expression being executed inside in each instance. Heres an example (not working, of course) ...


fn testLoop expr =
(
for x = 1 to 10 do expr
)

testLoop (print x)
testLoop (sum += x)


Is a way to package the for loop into a function and be able to pump in a different expression each time? Or do I just have to write out the for loop each time I want to use it?

Thank you!

Mathieson
06-17-2007, 05:17 PM
Nevermind, figured it out.


sum = 0

fn testPrint val =
(
print val
)

fn testSum val =
(
sum += val
)

fn testLoop tester =
(
for x = 1 to 10 do tester x
)


testLoop (testPrint)
testLoop (testSum)
print sum

Mathieson
06-17-2007, 05:22 PM
Actually, that still doesn't help me for instances where my other functions require more than one variable input..


sum = 0

fn testSum meh val =
(
sum += (val + meh)
)

fn testLoop tester =
(
for x = 1 to 10 do tester x
)

testLoop (testSum 3)
print sum

fabman
06-17-2007, 05:33 PM
Have you tried passing the expression as a string, and evaluating that string inside the function with eval?
I don't have max installed on this laptop so I can't test it, but maybe it could work.

Mathieson
06-17-2007, 05:46 PM
Cool! I was trying that earlier when I was trying to pass the variable x in from outside the function, but wasn't having success (for reasons which are obvious to me now). Hadn't thought to try it since, but just did for passing in a known variable and it worked! Thanks!


sum = 0

fn testSum val step step2 =
(
sum += (val + step + step2)
)

fn testLoop tester =
(
for x = 1 to 10 do execute(tester + (x as string))
)

testLoop "testSum 3 4 "
print sum

CGTalk Moderation
06-17-2007, 05:46 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.