For...To...Step....Next Loops
Monkey Forums/Monkey Programming/For...To...Step....Next Loops
| ||
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? |
| ||
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. |
| ||
For Local i:Int = 0 Until 10 Print i i += 1 Next |
| ||
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 |
| ||
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 |
| ||
Thanks Dima, after I thought about it for a sec I came up with the same approach as you. |
| ||
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 |
| ||
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. |
| ||
True. Hence the quotation i placed. |