如何在Lua中跳出for循环

我有以下代码:

  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

当“duplicate”设置为true时,我想完全退出for循环。现在,即使它找到匹配项,它也会循环遍历表中的所有值。

我尝试使用break语句,但我想它正在打破“if”语句。

我考虑使用do while循环,我可以将其包装在整个for循环中,但我仍然需要一种方法来退出for。

谢谢。

点赞
用户869951
用户869951

我尝试了以下代码:

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

它能正常运行:

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

正如您所看到的,它跳过了 adoe3。因此错误在其他地方:可能是 var2 或你的名字不是你想象中的那样(例如名称值是字符串,但 var2 是数字),或者你没有与之匹配的键。

2014-05-17 14:52:37