Help - Search - Members - Calendar
Full Version: Ruby, how to apply changes on every other number in loops?
RPG RPG Revolution Forums > Scripting > Script Development and Support
Titanhex
I know how to do this with a loop and if statement, but not with a for iterator.

Anyone able to tell me how to do a loop that can do this?
CODE
for i in min..max
  $num1 = i
  Do Something
end
Where i is an odd or even or whatever number.

The if equivalent would be
CODE
i = 0
loop
i += 2
  $varnum = i
  if i >= 20
   break
  end
end


I'm looking for some smaller version of that code.
Night5h4d3
CODE
for i in min..max
  next if (i % 2) != 0
  $num1 = i
  Do Something
end

for evens, and:
CODE
for i in min..max
  next if (i % 2) != 1
  $num1 = i
  Do Something
end

for odds. This basically jumps to the start of the loop again if i / 2 has a remainder (meaning it's odd) or not (meaning its even).

Alternately, you can do:

CODE
i = min
until i == max
  $num1 = i
  Do Something
  i += 2
end
Titanhex
Awesome, thanks. That's what I wanted.

Also is there a way to check every other number without introducing a new variable?
Night5h4d3
Well, with any loops you need a counter variable, like i. So basically, unless you have another variable to use as a loop counter, no. 'i' is used because it wont mess up any other local variable, and if you use it with a for loop, it's scope is only that for loop.

But either way, there's no reason why you should need to worry about introducing i as a loop counter, the act of looping takes more time then the creation of a new variable to count.

Hope that helps.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2013 Invision Power Services, Inc.