Star Brood
Star Brood

Reputation: 51

Lua: Access the for loop variable from outside of the loop

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?

Upvotes: 3

Views: 978

Answers (1)

Zakk
Zakk

Reputation: 2063

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

Upvotes: 3

Related Questions