Difference between revisions of "Io.lines"

From GiderosMobile
(mostly formatting :-))
m (Text replacement - "</source>" to "</syntaxhighlight>")
 
(3 intermediate revisions by 2 users not shown)
Line 5: Line 5:
 
=== Description ===
 
=== Description ===
 
Opens the given file name in read mode and returns an iterator function. Each time the iterator function is called, it returns a new line from the file.
 
Opens the given file name in read mode and returns an iterator function. Each time the iterator function is called, it returns a new line from the file.
<source lang="lua">
+
 
 +
The call '''io.lines()''' (with no file name) is equivalent to '''io.input():lines()''' that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends.
 +
<syntaxhighlight lang="lua">
 
(function) = io.lines(filename)
 
(function) = io.lines(filename)
</source>
+
</syntaxhighlight>
  
 
+
When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.
The construction
 
<source lang="lua">
 
for line in io.lines(filename) do body end
 
</source>
 
will iterate over all lines of the file. When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.
 
 
 
The call '''io.lines()''' (with no file name) is equivalent to '''io.input():lines()''' that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends.
 
  
 
=== Parameters ===
 
=== Parameters ===
Line 26: Line 21:
 
=== Example ===
 
=== Example ===
 
'''Iterates over all lines of a file'''
 
'''Iterates over all lines of a file'''
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
for line in io.lines(filename) do
 
for line in io.lines(filename) do
-- do stuff
+
-- body
 
end
 
end
</source>
+
</syntaxhighlight>
  
 
{{Io}}
 
{{Io}}

Latest revision as of 14:30, 13 July 2023

Available since: Gideros 2011.6
Class: io

Description

Opens the given file name in read mode and returns an iterator function. Each time the iterator function is called, it returns a new line from the file.

The call io.lines() (with no file name) is equivalent to io.input():lines() that is, it iterates over the lines of the default input file. In this case it does not close the file when the loop ends.

(function) = io.lines(filename)

When the iterator function detects the end of file, it returns nil (to finish the loop) and automatically closes the file.

Parameters

filename: (string) filename to open optional

Return values

Returns (function) iterator function

Example

Iterates over all lines of a file

for line in io.lines(filename) do
	-- body
end