Difference between revisions of "love.filesystem.lines"

(Examples: Less confusing example. Changed separation character from tab to comma. Cleanup.)
m
 
Line 1: Line 1:
 +
{{newin|[[0.5.0]]|050|type=function}}
 
Iterate over the lines in a file.
 
Iterate over the lines in a file.
  

Latest revision as of 02:39, 21 October 2022

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