For...To...Step....Next Loops

Monkey Forums/Monkey Programming/For...To...Step....Next Loops

Arabia(Posted 2013) [#1]
This....

Local sx:int = -1
For Local i:Int = 100 To 1 Step sx
	Print i
Next


...throws up a compilation error "VarExpr(Local sx:Int) cannot be statically evaluated." Is there any way around this or is it just not possible to use a variable as your step size?


Dima(Posted 2013) [#2]
Monkey doesn't allow variable step with for loops. You could accomplish desired behavior using while loops and index variable that you keep track of yourself. Then you can increment that variable inside the loop using your variable step.


Shinkiro1(Posted 2013) [#3]
For Local i:Int = 0 Until 10
  Print i
  i += 1
Next



Arabia(Posted 2013) [#4]
Thanks guys.

Reason why I was asking was because I wanted to use a single for loop:

stepSize = 1
if x2 < x1 then stepSize *= -1
For x:int = x1 to x2 step stepSize
Next


So I guess I need to do this the long way?

if x2 < x1 then
  for x:int = x1 to x2 step -1
  next
else
  for x:int = x1 to x2
  next
endif



Dima(Posted 2013) [#5]
if step is either 1 or -1 it's pretty simple:
	Local x% = x1
	Local stp% = Sgn(x2-x1)
	While x <> x2
		x+= stp
	End



Arabia(Posted 2013) [#6]
Thanks Dima, after I thought about it for a sec I came up with the same approach as you.


darky000(Posted 2013) [#7]
Actually monkey "allows" variable in Step. It should, however, be a constant variable.

Const sx:Int = - 1

For Local i:Int = 100 To 1 Step sx
   Print i
Next



GfK(Posted 2013) [#8]
Actually monkey "allows" variable in Step. It should, however, be a constant variable.
Um... there is no such thing as a "constant variable" - the two words mean the bang-opposite of each other. Constants are evaluated to the specified value at compile time. They cannot be changed. They are not "variable".

@Arabia - to achieve what you're trying to do, consider switching to a While/Wend, or Repeat/Until loop.


darky000(Posted 2013) [#9]
True. Hence the quotation i placed.