How do I store the value of a for loop variable when the loop ends?

I am trying to find something in a loop in Lua and when I am done I need to use the location I found.

for j = 1,100 do
    <do some stuff>
    if <some test> then
            break
    end
end
if j >= 100 then
    return
end

      

Unfortunately, I am getting an error that suggests that the for

value j

is nil after the loop ends . How do I use the value that j has ended? Obviously, I could create an additional variable and assign it right before I break, but that just seems to be wrong and I've never seen another language that sets a loop variable to nil when the loop ends, so I'm wondering if there is the best way to achieve this.

+3


source to share


1 answer


The loop variable is displayed only inside the for loop block. You can work around this by creating another variable as suggested in PIL 4.3.4 Numeric value for .

  local index
  for j=1,100 do
     if j == 10 then
       index = j
     end
  end

      



Alternatively, if you are doing a general operation, then it is better to use an early return function.

     function find(tbl, val)
        for i, v in ipairs(tbl) do
          if v == val then
            return i
          end
        end
     end

      

+4


source







All Articles