Notifications
Clear all

[Closed] Creating a function for a for-loop

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!

4 Replies

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

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
 

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.

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