From the body of your loop its not clear to me what you are actually trying…
But from the headline of your question, I do guess, that you are trying to build an imperative loopp, which mutates some internal state from one iteration to the other.
The answer then is pretty simply: you cant! There is no mutability in elixir (well sometimes it seems as if, because of shadowing already bound names or tricky processes).
The more canonical way to do this, is to extract that into a function of its own which you call recursively and pass the changed “state” explicitely.
Your function could look like this one then:
defp do_loop(i, state \\ {0, []})
defp do_loop(0, state), do: state
defp do_loop(i, {num, list}) when rem(i, 2) == 0, do: do_loop(i - 1, {num + i, list})
defp do_loop(i, {num, list}), do: do_loop(i - 1, {num, [i|list]})
defp do_loop(current, ending, ...) when current >= ending, do: #finished
defp do_loop(current, ending, ...) do
# do something with ...
do_loop(current + 5, ending, ...)
end
And you can even pass in a stepsize by adding another argument:
defp do_loop(current, ending, stepsize, ...) when current >= ending, do: #finished
defp do_loop(current, ending, stepsize, ...) do
# do something with ...
do_loop(current + stepsize, ending, ...)
end
Please try to keep your working state as an argument to the function, do not try to keep anythin in an Agent or Process-Dictionary. That will make it hard to test and reason about the function once it has passed a certain complexity!