Page 1 of 1

Read Line with Love File

Posted: Thu Feb 22, 2018 3:46 pm
by Wilma456
The Normal io API of LUA offers for reading file:read("*l"), file:read("*a") and file:read(number). But Love File only offer file:read(number). How can I read a Line and all? I had try this for reading lines:

Code: Select all

local str = ""
while true do
	local c = file:read(1)
	if c == "\n" or c == "" then
		break
	else
		str = str..c
	end
end
return str
But this is to slow. I know, that Love2d offers a File Iterator, but with the Iterator I can't read single Bytes.

I know, the io API is also aviable in Love, but it use the real path on the computer and not the virtual file system of Love.

Re: Read Line with Love File

Posted: Thu Feb 22, 2018 4:03 pm
by grump
There is love.filesystem.lines, but it's very slow in 0.10.2.

This is a faster substitute I used when I needed to parse 20k+ CSV lines:

Code: Select all

function lines(fn)
	local data = assert(love.filesystem.read(fn))
	for line in string.gmatch(data, "[^\n]+") do
		table.insert(result, line)
	end

	return result
end

Re: Read Line with Love File

Posted: Thu Feb 22, 2018 4:21 pm
by Wilma456
It looks like your function can not support reading single Bytes. I need reading single bytes and reading single lines in the smae hadle like the io API.

Re: Read Line with Love File

Posted: Thu Feb 22, 2018 5:42 pm
by grump
If the file is not huge, read the whole file with love.filesystem.read, then either iterate over the resulting string or use string.match/string.find to locate delimiters. That should be faster than reading single bytes one by one.

Maybe a serialization lib is what you need; I wrote this library to parse arbitrary binary data from strings. It's very low level though and best suited for files that can be read at once. If the interface is too verbose or doesn't fit your use case, there are several other alternatives available (binser, bitser, struct). Searching the forum and/or github should yield some results.

Re: Read Line with Love File

Posted: Thu Feb 22, 2018 7:42 pm
by zorg
Reading single bytes can be slow as hell; reading a big chunk into memory, then iterating over a memory area will always be faster than that;
That said, with string patterns, you can still extract single bytes from said loaded chunk, as well as lines and any other pattern that lua's capable of matching.