lua-users home
lua-l archive

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




On 24 Mar 2022, at 18:50, Egor Skriptunoff <egor.skriptunoff@gmail.com> wrote:

On Thu, Mar 24, 2022 at 4:51 PM Thijs Schreijer wrote:
This means that reading a Windows based text file, with CRLF as
line endings, the returned lines will have a trailing CR (char 13).

I can not reproduce this problem.
Everything works as expected on Windows.

Here’s my test code:


print(_VERSION)
local CR = string.char(13)
local LF = string.char(10)

local function writefile(name, content)
  local f = io.open(name, "w")
  f:write(content)
  f:close()
end

local function readfile(name, mode)
  local f = io.open(name, "r")
  while f do
    local l = f:read(mode)
    if l then
      local le = l:gsub(CR, "+CR"):gsub(LF, "+LF")
      if le:sub(1,1) == "+" then
        le = le:sub(2,-1)
      end
      print(#l, le)
    else
      f:close()
      f = nil
    end
  end
end

local lines = {               -- "*L" result:
  "1234567890"..LF,           -- 1 line, 11 bytes
  "1234567890"..LF..CR..LF,   -- 2 lines, 11 bytes + 2 bytes
  "1234567890"..CR..LF,       -- 1 line, 12 bytes
  "1234567890"..CR..LF..LF,   -- 2 lines, 12 bytes + 1 byte
  "1234567890"                -- 1 line, 10 bytes
}
lines = table.concat(lines)

writefile("test.txt", lines)
for _, mode in ipairs { "*l", "*L" } do
  print("\nTesting mode: "..mode)
  readfile("test.txt", mode)
end



Result on Mac:
Lua 5.3

Testing mode: *l
10	1234567890
10	1234567890
1	CR
11	1234567890+CR
11	1234567890+CR
0	
10	1234567890

Testing mode: *L
11	1234567890+LF
11	1234567890+LF
2	CR+LF
12	1234567890+CR+LF
12	1234567890+CR+LF
1	LF
10	1234567890
Program completed in 0.16 seconds (pid: 86623).


Result on Windows:

Lua 5.3

Testing mode: *l
10	1234567890
10	1234567890
1	CR
11	1234567890+CR
11	1234567890+CR
0	
10	1234567890

Testing mode: *L
11	1234567890+LF
11	1234567890+LF
2	CR+LF
12	1234567890+CR+LF
12	1234567890+CR+LF
1	LF
10	1234567890
Program completed in 0.23 seconds (pid: 5044).