love.filesystem.lines

Available since LÖVE 0.5.0
This function is not supported in earlier versions.

Iterate over the lines in a file.

Function

Synopsis

iterator = love.filesystem.lines( name )

Arguments

string name
The name (and path) of the file

Returns

function iterator
A function that iterates over all the lines in the file, returning the line with newlines stripped (if the line ends with \r\n, both are stripped independently of the OS)

Examples

Load highscore list

local highscores = {}
for line in love.filesystem.lines("highscores.txt") do
  table.insert(highscores, tonumber(line))
end

Load comma separated values

local function splitCsvLine(line)
	local values = {}

	for value in line:gmatch("[^,]+") do -- Note: We won't match empty values.
		-- Convert the value string to other Lua types in a "smart" way.
		if     tonumber(value)  then  table.insert(values, tonumber(value)) -- Number.
		elseif value == "true"  then  table.insert(values, true)            -- Boolean.
		elseif value == "false" then  table.insert(values, false)           -- Boolean.
		else                          table.insert(values, value)           -- String.
		end
	end

	return values
end

local function loadCsvFile(filename)
	local csv = {}
	for line in love.filesystem.lines(filename) do
		table.insert(csv, splitCsvLine(line))
	end
	return csv
end

--[[ cool.csv:
Foo,Bar
true,false,11.8
]]
local csv = loadCsvFile("cool.csv")
for row, values in ipairs(csv) do
	print("row="..row.." count="..#values.." values=", unpack(values))
end

See Also


Other Languages