All answers / comments so far only suggested while loops; here's two more ways of working around this problem:
If you always have the same step size, which just isn't 1
, you can explicitly give the step size as in for i =
start
,
end
,
step
do … end
, e.g. for i = 1, 10, 3 do …
or for i = 10, 1, -1 do …
. If you need varying step sizes, that won't work.
A "problem" with while
-loops is that you always have to manually increment your counter and forgetting this in a sub-branch easily leads to infinite loops. I've seen the following pattern a few times:
local diff = 0
for i = 1, n do
i = i+diff
if i > n then break end
-- code here
-- and to change i for the next round, do something like
if some_condition then
diff = diff + 1 -- skip 1 forward
end
end
This way, you cannot forget incrementing i
, and you still have the adjusted i
available in your code. The deltas are also kept in a separate variable, so scanning this for bugs is relatively easy. (i
autoincrements so must work, any assignment to i
below the loop body's first line is an error, check whether you are/n't assigning diff
, check branches, …)