Why does this exit the function early?

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Why does this exit the function early?

Paul Butler
Newbie question.....

Why does the "break" end the function?
I was expecting it to count to 10 and just skip over 5.



function doThis()
  local count = 0
  while true do
    count = count + 1
        if count == 5 then break end
        print(count)
        if count == 10 then return end
  end
  print("why are we here?")
end

doThis()


--
-paul
Reply | Threaded
Open this post in threaded view
|

Re: Why does this exit the function early?

Mike Crowe
You were using "break" as if it were "continue", which lua doesn't have.

break terminates the while loop.

Paul Butler wrote:

> Newbie question.....
>
> Why does the "break" end the function?
> I was expecting it to count to 10 and just skip over 5.
>
>
>
> function doThis()
>   local count = 0
>   while true do
>     count = count + 1
> if count == 5 then break end
> print(count)
> if count == 10 then return end
>   end
>   print("why are we here?")
> end
>
> doThis()
>
>
>  
Reply | Threaded
Open this post in threaded view
|

Re: Why does this exit the function early?

Stefan Brantschen
In reply to this post by Paul Butler
Hi

On 18 Jun 2009, at 19:08, Paul Butler wrote:

> Why does the "break" end the function?
> I was expecting it to count to 10 and just skip over 5.

See <http://www.lua.org/manual/5.1/manual.html#2.4.4>: "The break  
statement is used to terminate the execution of a while, repeat, or  
for loop, skipping to the next statement after the loop"

With regards
-- Stefan