Problem reading lines from a file...

Hi All

I am trying read from a file, but the the read() function appears to be returning the whole file, and not each line as the LUA documentation suggests.

Here is my test program…

– File Test

function setup()

home = os.getenv("HOME")
file = home.."/Documents/DataSet.txt"

fh = io.open(file,"w")
fh:write('"yippee","tangle"')
fh:write('123.45,0.34')
fh:write("test")
fh:close()

fh = io.open(file,"r")
line1 = fh:read() 
print(line1)
line2 = fh:read() 
print(line2)
line3 = fh:read() 
print(line3)
fh:close()

end

function draw()

end

The program generates the following output…

“yippee”,"tangle"123.45,0.34test
nil
nil

I am not sure what I am doing wrong. I have checked the file DataSet.txt using iExplorer and it has three lines. But when I read the file, I get the whole file on the first read, and nil thereafter as the end of file has been reached.

Any suggestions or help would be most welcome.

Cheers

Cameron

The output should read … “yippee”,"tangle"123.45,0.34test [new line] nil [new line] nil …

@alacazam - try adding the newline char after each write, eg

fh:write('"yippee","tangle"',"\
")

The read function has different parameters you can try.


file:read (···)

Reads the file file, according to the given formats, which specify what to read. For each format, the function returns a string (or a number) with the characters read, or nil if it cannot read data with the specified format. When called without formats, it uses a default format that reads the next line (see below).

The available formats are

"*n": reads a number; this is the only format that returns a number instead of a string.
"*a": reads the whole file, starting at the current position. On end of file, it returns the empty string.
"*l": reads the next line skipping the end of line, returning nil on end of file. This is the default format.
"*L": reads the next line keeping the end of line (if present), returning nil on end of file.
number: reads a string with up to this number of bytes, returning nil on end of file. If number is zero, it reads nothing and returns an empty string, or nil on end of file.