Search code examples
while-loopluaiteratorinfinite-loop

This stateless iterator supposed to be an infinite loop without a conditional statement, but it don't


In the previous question, I have asked about an iterator that would create an infinite loop(print nil), and learnt about how important the conditional statement is. Well, for some reasons,this iterator didn't create the infinite loop despite not having the conditional statement.


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

Well, I assume that while was involved with the reason why this iterator didn't become an infinite loop. Like, Is while act as the conditional statement ? Had while used break after it got nil?


Solution

  • Your code ends up in an infinite loop.

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

    will run forever as soon as soon as you've reached the last element of s[pos].