如何解决这个无状态的迭代器应该是没有条件语句的无限循环,但它不会
在上一个问题中,我询问了一个将创建无限循环(print nil
)的迭代器,并了解了条件语句的重要性。嗯,由于某些原因,即使没有条件语句,此迭代器也不会创建无限循环。
local function OnlyStrings(s)
local function Iter(s,pos)
pos = pos + 1
--[[After assigned pos + 1 to pos,"while" will look at the condition again then see
whether it's a string or not -- ]]
while type(s[pos]) ~= "string" do
pos = pos + 1
end
return pos,s[pos]
--pos is the control variable,it's supposed to + 1 forever without a conditional statement
end
return Iter,s,0
end
local t = {"bruh",1,2,"yep",true}
for i,string in OnlyStrings(t) do
print(string)
--[[bruh
yep ]] --
end
好吧,我假设while
涉及了此迭代器未成为无限循环的原因。像while
充当条件语句吗? while
在使用break
之后是否使用过nil
?
解决方法
您的代码最终陷入无限循环。
while type(s[pos]) ~= "string" do
pos = pos + 1
end
一旦到达s[pos]
的最后一个元素,它将永远运行。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。