break for iterators

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

break for iterators

Alexey Malyshev
HI!

This code example causes error after ~500 for loop iterations.

for k=1,1000 do
    for line in io.lines() do
        break
    end
end

When iteration cycle breaks, file handles doesn't close.
Does break keyword wrong for iterator's loop?


Reply | Threaded
Open this post in threaded view
|

Re: break for iterators

Shmuel Zeigerman-2
Alexey Malyshev wrote:
This code example causes error after ~500 for loop iterations.

for k=1,1000 do
    for line in io.lines() do
        break
    end
end

When iteration cycle breaks, file handles doesn't close.
Does break keyword wrong for iterator's loop?

It isn't wrong, but the "generic for" just terminates the loop on breaks, so the file remains open until the garbage collector will close it. The following example should work (untested):

> for k=1,1000 do
>     for line in io.lines() do
>         break
>     end
>     collectgarbage"collect"
> end

Wouldn't it be possible to enhance the "generic for" by adding an extra "break" call to the iterator (with a nil or false argument), to let it do the cleanup when needed? That may break the existing applications though (no pun intended).

--
Shmuel

Reply | Threaded
Open this post in threaded view
|

Re: break for iterators

Ben Sunshine-Hill
On Fri, Feb 22, 2008 at 11:41 AM, Shmuel Zeigerman <[hidden email]> wrote:
> It isn't wrong, but the "generic for" just terminates the loop on
> breaks, so the file remains open until the garbage collector will close
> it. The following example should work (untested):
>
>
>  > for k=1,1000 do
>  >     for line in io.lines() do
>  >         break
>  >     end
>  >     collectgarbage"collect"
>  > end
>
> Wouldn't it be possible to enhance the "generic for" by adding an extra
> "break" call to the iterator (with a nil or false argument), to let it
> do the cleanup when needed? That may break the existing applications
> though (no pun intended).

I would think the easier fix would simply be for io calls which fail
to allocate a file handle to collectgarbage and try again.

Reply | Threaded
Open this post in threaded view
|

Re: break for iterators

Mark Hamburg-4
In reply to this post by Shmuel Zeigerman-2
I can certainly appreciate the desire to get notification for the iterator
at the end of the loop, but consider that in addition to break one probably
also needs to handle return and exceptions throws. It gets messy pretty
fast.

Mark