【发布时间】:2020-09-14 11:46:33
【问题描述】:
在上一个问题中,我询问了一个会创建无限循环的迭代器(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 在得到nil 之后使用了break?
【问题讨论】:
-
当我尝试时它一直循环直到程序中止......
-
啊,我明白了,我尝试在
while循环中添加print("pos"),它一直在打印,直到我停止程序。它打印了两次,所以我认为Iter不是无限循环
标签: while-loop lua iterator infinite-loop