aboutsummaryrefslogtreecommitdiff
path: root/testes/files.lua
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-11-07 14:42:05 -0200
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-11-07 14:42:05 -0200
commit7f6f70853c8a2730fca2e95d5968ad52cf470bda (patch)
tree948147a9cf6a5c5eb34232e7547c310eb06eadea /testes/files.lua
parentb8fed93215a23a3f443c5b0126f0de1725771b44 (diff)
downloadlua-7f6f70853c8a2730fca2e95d5968ad52cf470bda.tar.gz
lua-7f6f70853c8a2730fca2e95d5968ad52cf470bda.tar.bz2
lua-7f6f70853c8a2730fca2e95d5968ad52cf470bda.zip
To-be-closed variable in 'for' loop separated from the state
The variable to be closed in a generic 'for' loop now is the 4th value produced in the loop initialization, instead of being the loop state (the 2nd value produced). That allows a loop to use a state with a '__toclose' metamethod but do not close it. (As an example, 'f:lines()' might use the file 'f' as a state for the loop, but it should not close the file when the loop ends.)
Diffstat (limited to 'testes/files.lua')
-rw-r--r--testes/files.lua37
1 files changed, 36 insertions, 1 deletions
diff --git a/testes/files.lua b/testes/files.lua
index e68eb9b8..34fcf851 100644
--- a/testes/files.lua
+++ b/testes/files.lua
@@ -200,7 +200,7 @@ return x + y * z
200assert(f:close()) 200assert(f:close())
201f = coroutine.wrap(dofile) 201f = coroutine.wrap(dofile)
202assert(f(file) == 10) 202assert(f(file) == 10)
203print(f(100, 101) == 20) 203assert(f(100, 101) == 20)
204assert(f(200) == 100 + 200 * 101) 204assert(f(200) == 100 + 200 * 101)
205assert(os.remove(file)) 205assert(os.remove(file))
206 206
@@ -422,6 +422,41 @@ assert(load(io.lines(file, "L"), nil, nil, t))()
422assert(t.a == -((10 + 34) * 2)) 422assert(t.a == -((10 + 34) * 2))
423 423
424 424
425do -- testing closing file in line iteration
426
427 -- get the to-be-closed variable from a loop
428 local function gettoclose (lv)
429 lv = lv + 1
430 for i = 1, math.maxinteger do
431 local n, v = debug.getlocal(lv, i)
432 if n == "(for toclose)" then
433 return v
434 end
435 end
436 end
437
438 local f
439 for l in io.lines(file) do
440 f = gettoclose(1)
441 assert(io.type(f) == "file")
442 break
443 end
444 assert(io.type(f) == "closed file")
445
446 f = nil
447 local function foo (name)
448 for l in io.lines(name) do
449 f = gettoclose(1)
450 assert(io.type(f) == "file")
451 error(f) -- exit loop with an error
452 end
453 end
454 local st, msg = pcall(foo, file)
455 assert(st == false and io.type(msg) == "closed file")
456
457end
458
459
425-- test for multipe arguments in 'lines' 460-- test for multipe arguments in 'lines'
426io.output(file); io.write"0123456789\n":close() 461io.output(file); io.write"0123456789\n":close()
427for a,b in io.lines(file, 1, 1) do 462for a,b in io.lines(file, 1, 1) do