lua-users home
lua-l archive

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


2017-09-05 15:13 GMT+02:00 Shmuel Zeigerman <shmuz@013net.net>:
> I wonder why the first read from an empty file returns nil rather than an
> empty string.
> E.g. fp:read(10) --> nil
>
> If the zero-sized file exists then it can be interpreted as a file
> containing an empty string (IMHO).
>
> --
> Shmuel

An empty file is an exceptional file in the sense that its beginning
and its end is the same: position 0. fp:seek"set" and fp:seek"end"
put you in the same place.

To have fp:read(10) return nil when you are at the end of the file
is clearly the right thing to do. It is so much the right thing that
the exceptional behaviour of fp:read"a" is specifically documented
in the manual.

To have fp:read(10) return non-nil when you are reading for the
first time from an empty file would require that Lua needs to
know whether you are reading for the first time, not merely
that the file position is 0. Otherwise

repeat rec=fp:read(10) until not rec

will produce an infinite loop on an empty file (but not on others).