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.)
This commit is contained in:
Roberto Ierusalimschy
2018-11-07 14:42:05 -02:00
parent b8fed93215
commit 7f6f70853c
6 changed files with 76 additions and 29 deletions

View File

@@ -371,6 +371,8 @@ do
x = x - 1
if x > 0 then return x end
end,
nil, -- state
nil, -- control variable
function () -- closing function
numopen = numopen - 1
end
@@ -392,12 +394,16 @@ do
-- repeat test with '__open' metamethod instead of a function
local function open (x)
numopen = numopen + 1
local state = setmetatable({x},
{__close = function () numopen = numopen - 1 end})
return
function (t) -- iteraction function
t[1] = t[1] - 1
if t[1] > 0 then return t[1] end
end,
setmetatable({x}, {__close = function () numopen = numopen - 1 end})
state,
nil,
state -- to-be-closed
end
local s = 0