【问题标题】:This stateless iterator supposed to be an infinite loop without a conditional statement, but it don't这个无状态迭代器应该是一个没有条件语句的无限循环,但它没有
【发布时间】: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


【解决方案1】:

您的代码最终陷入无限循环。

while type(s[pos]) ~= "string" do 
  pos = pos + 1 
end 

一旦您到达s[pos] 的最后一个元素,就会永远运行。

【讨论】:

  • 啊,我明白了,我认为这不是无限循环,因为它只打印了两次。但是由于while循环而产生了循环,因此它永远不会到达return pos, s[pos
猜你喜欢
  • 2017-01-05
  • 2018-04-09
  • 2020-09-01
  • 2021-10-15
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
相关资源
最近更新 更多