Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to break out of a for loop in lua

Tags:

for-loop

lua

i have the following code:

  for k, v in pairs(temptable) do
         if string.match(k,'doe') then 
              if v["name"] == var2 then
                     txterr =  "Invalid name for "..k
                     duplicate = true
             end
             if duplicate then
                     break
             end
         end
    end 

when duplicate is set to true, i want to exit the for loop all together. right now, it just loops through all the values in the table even if it finds a match.

i tried using the break statement but i think it is breaking out of the "if" statement.

i was thinking about a do while loop i could wrap around the entire for loop but i would still need a way to break out of the for.

thanks.

like image 689
dot Avatar asked May 16 '14 18:05

dot


1 Answers

I tried the following:

temptable = {a=1, doe1={name=1}, doe2={name=2}, doe3={name=2}}
var2 = 1
for k, v in pairs(temptable) do
    print('trying', k)
    if string.match(k,'doe') then 
        print('match doe', k, v.name, var2)
        if v["name"] == var2 then
            txterr =  "Invalid name for "..k
            duplicate = true
            print('found at k=', k)
        end
        if duplicate then
            print('breaking')
            break
        end
    end
end 

and it works:

trying  doe2
match doe   doe2    2   1
trying  doe1
match doe   doe1    1   1
found at k= doe1
breaking

As you can see it skipped a and doe3. The error is therefore elsewhere: var2 or your names are not what you think (like the name values are strings whereas var2 is number), or you don't have any keys that match.

like image 181
Oliver Avatar answered Oct 03 '22 06:10

Oliver