lua-users home
lua-l archive

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


2009/8/25 Michal Kolodziejczyk <miko@wp.pl>:
> Alexander Gladysh wrote:

>> local f = assert(io.open("123.txt"))
>> for l in f:lines() do

> Firs of all, I am wondering why it works ion the first place. According
> to the manual, you need io.lines(filename), not io.lines(filehandle)!
> If it works with filehandle, it is not documented, so the behaviour in
> unexpected.

There is file:lines() and there is io.lines() -- two different
functions, behaving slightly differently.

http://www.lua.org/manual/5.1/manual.html#pdf-io.lines
http://www.lua.org/manual/5.1/manual.html#pdf-file:lines

>> Looks like subsequent calls for :lines() on the same handle are ignored.

> As it is with other iterators, which - when finished - return nil. This
> is expected.

Hm. I'm not sure I get you correctly. I always thought that, in this
case, iterator is that :lines() returns, not the function itself.
After all, each call to pairs() always return new iterator. Not?

>> So, the correct way is to re-open nested file handles on each:

> The io.lines() manual says: "When the iterator function detects the end
> of file, it returns nil (to finish the loop) and automatically closes
> the file.".

Yes, indeed, for io.lines(). But I'm using file.lines(), for which the
manual explicitly states (see link above):

    Unlike io.lines, this function does not close the file when the loop ends.

It looks like while file.lines perhaps does not close the file, it
does not seek it back to beginning. Furthermore, it looks like all
iterators to the same file do use the same file position pointer.

> So I am expecting the behaviour you observe. You seem to expect that
> after the end of file, iterator closes and reopens the file, rewinding
> to the beginning. But it is not true, if you want to read the file many
> times in your internal loop, you need to open it many times, as you have
> just noticed.

See above.

Alexander.