How to exit a for loop in 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 end the for loop. right now, it just scans all the values ​​in the table, even if it finds a match.

I tried using the break statement, but I think it exits the if statement.

I was thinking of a do while loop that I could wrap around a for loop, but I still need a way to exit the mode.

thank.

+4
source share
1 answer

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

, a doe3. : var2 , (, , var2 - ), , .

+2

Source: https://habr.com/ru/post/1540887/


All Articles