我有以下代码:
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语句,但我认为它正在突破"如果"声明。
我正在考虑做一个while循环我可以绕过整个for循环,但我仍然需要一种方法来突破for。
感谢。
答案 0 :(得分:3)
我尝试了以下内容:
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
你可以看到它跳过a和doe3。因此错误在其他地方:var2或你的名字不是你想的(比如名字值是字符串,而var2是数字),或者你没有任何匹配的键。