State in generic 'for' acts as a to-be-closed variable

The implicit variable 'state' in a generic 'for' is marked as a
to-be-closed variable, so that the state will be closed as soon
as the loop ends, no matter how.

Taking advantage of this new facility, the call 'io.lines(filename)'
now returns the open file as a second result. Therefore,
an iteraction like 'for l in io.lines(name)...' will close the
file even when the loop ends with a break or an error.
This commit is contained in:
Roberto Ierusalimschy
2018-10-31 14:54:45 -03:00
parent e073cbc2e5
commit 947a372f58
5 changed files with 111 additions and 24 deletions

View File

@@ -462,13 +462,13 @@ X
- y;
]]:close()
_G.X = 1
assert(not load(io.lines(file)))
assert(not load((io.lines(file))))
collectgarbage() -- to close file in previous iteration
load(io.lines(file, "L"))()
load((io.lines(file, "L")))()
assert(_G.X == 2)
load(io.lines(file, 1))()
load((io.lines(file, 1)))()
assert(_G.X == 4)
load(io.lines(file, 3))()
load((io.lines(file, 3)))()
assert(_G.X == 8)
print('+')