lua-users home
lua-l archive

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


Using a global substitution paired with an anchor that limits it to the end of string feels somewhat odd to me (also shouldn't it be "\r" instead of "\\r" in the pattern?). As an alternative I'd suggest simply using matching:

line = line:match"(.*)\r?"
On 24.03.22 19:55, Oliver Kroth wrote:
Hi,

opening a text file in non-binary mode (no 'b' in mode) on Linux won't help you with a file that was written with CR+LF as line endings.
I use to snip off a terminating \r:

line = file:read('*l')
if not line then break end
line = line:gsub( '\\r$', '' )

Funny enough, the socket filter '*l' removes all '\r' characters, thus it may indeed may come unexpected that file:read('*l') does not.

If one has to read a lot of files line by line, one may consider to define a iterator factory lines that crates iterators that snip off the terminating '\r', like:

for line in lines( file ) do
 ...
end


Regards,

Oliver

Am 24.03.22 um 16:02 schrieb Francisco Olarte:
Mitchell:

On Thu, 24 Mar 2022 at 15:39, Mitchell <lists@triplequasar.com> wrote:
I don't have a Windows box to test this on, but if I recall correctly, opening the file in binary mode on Windows should allow 'l' to also trim '\r'. I could be misremembering though.
It is the other way round. Opening a file in binary gives you
uninterpreted bytes. The C runtime ( on which lua builds ) is supposed
to translate whatever you os uses for end of line into a '\n'. So a
file "ab\012bc\015de\015\012" is read the same in every OS in binary
mode, but you may have problems (CP/M like CRLF, unixlike LF or
Macintosh(classic, not osx) CR ).
In default (text) mode they could be read differently. Also, normally
it is not a good idea to use binary mode for text files, or viceversa.

Francisco Olarte.






Cheers,
Mitchell