lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Friday 18 March 2011 18:15:11 Duncan Cross wrote:
> On Fri, Mar 18, 2011 at 10:04 PM, mitchell <code@caladbolg.net> wrote:
> > I want to iterate over the lines in a file, but break out if a certain
> > condition is true. The documentation says the EOF is detected and the
> > file is closed. If I break before the EOF is detected, is the file not
> > closed? I don't want to leave open file references in my Lua state.
> > 
> > for line in io.lines(filename) do
> >  if condition then break end
> >  ...
> > end
> > 
> > Thanks,
> > mitchell
> 
> Yes, the file handle will still be open, at least until the file
> object is garbage collected. There is no way for an iterator to detect
> a broken loop and run cleanup code, so you will need to make sure the
> handle is closed explicitly.

Or you can just set a flag in the loop to prevent processing lines after 
whatever condition happens. Or (drum roll please), you can use something like 
my relevant_lines() iterator described at 
http://www.troubleshooters.com/codecorn/lua/luaclosures.htm#_A_Practical_Line_Skipper_Iterator

SteveT

Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt