3

I would like to use a for-loop in Lua, but be able to identify what the last iterated value was:

local i
for i=0,10 do
    if i==5 then break end
end
print(i) --always prints nil

Is there some way to prevent "i" from being re-declared in the for loop block, instead of shadowing my upvalue of the same name?

Currently, I have to use a while loop to achieve the expected results, which defeats the clarity of the for loop's syntax. Is this just another Lua caveat one has to expect as part of its language quirks?

Star Brood
  • 31
  • 4
  • 2
    Yes this is a lua caveat: [The loop variable v is local to the loop; you cannot use its value after the for ends or is broken. If you need this value, assign it to another variable before breaking or exiting the loop.](https://www.lua.org/manual/5.1/manual.html#2.4.5) – shingo Jul 12 '22 at 10:37
  • Thank you! I guess I shouldn't hate on the while loop, then, as it's simpler under-the-hood anyway. – Star Brood Jul 12 '22 at 10:49
  • breaking a loop prematurely when the control variable reaches a certain value doesn't make sense. ajdust the loops limit instead. if that's just a placeholder for a different condition the question arises why you don't use a nother name for the control variable to avoid shadowing variables for the bigger scope. I cannot make sense of your post – Piglet Jul 12 '22 at 13:55

1 Answers1

3

i is local to the for-loop, meaning that you cannot access is when the loop terminates.

If you want to know what the last iterated value was, you have to save it in another variable:

local last
for i = 0, 10 do
    if i == 5 then
        last = i
        break
    end
end

print(last) --> 5
Zakk
  • 1,935
  • 1
  • 6
  • 17
  • Thank you! I was hoping there might be some kind of method to somehow "return" the local variable when the loop exits. The "while" loop is the lesser of two evils in the long run when I need this utility. – Star Brood Jul 12 '22 at 10:52