4

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?

3

1 Answer 1

4

i is local to the for-loop, meaning that you cannot access it 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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.