Interaction between 'io_readline' and 'io.lines' in generic 'for' loop (Lua 5.4.7)

48 views
Skip to first unread message

Jure Bagić

unread,
Mar 31, 2025, 10:58:28 PM3/31/25
to lua-l
As the title suggests, upon looking at the source of Lua 5.4.7 implementation,
it is not so clear to me how the error is not raised in the generic 'for'
loop after the iteration function 'io_readline' returns the 'nil' after
hitting end of file.

For example (taken from upstream test files):

```
local file = io.open("example.txt");
n = 0;
for l in io.lines(file) do
io.write(l, "\n");
n = n + 1;
end
```

to my understanding, the above, 'io.lines(file)' will return iteration
function, placeholder 'nil' values for state and control variable and
finally a filehandle as the 4th value that the generic 'for' will insert
into the 'tbclist' before the iteration function is called by 'OP_TFORCALL',
thus preserving the 4th value by copying the 4 values for the new call.

Now here is the confusing part for me to understand, after iteration
function 'io_readline' reads the whole file (hits end of file), it will
close the file (by calling 'aux_close') thus marking the filehandle as
"closed". However, the generic 'for' will also try to close the filehandle
(by calling 'f_close') and this will in turn raise error (in 'tofile')
"attempt to use a closed file".

Except this is not what happens, Lua handles this just fine.
I would appreciate any explanation on this, I know I am missing something.
-- Jure
signature.asc

Jure Bagić

unread,
Mar 31, 2025, 11:04:06 PM3/31/25
to lua-l
Excuse me, in the example, I am passing the filename not the actual
filehandle, so then

```
local file = "example.txt";
```

--
Jure
signature.asc

Jure Bagić

unread,
Mar 31, 2025, 11:29:12 PM3/31/25
to lua-l
I should really stop myself from looking at the source code at 5 am.
The actual '__close' metamethod is 'f_gc' not the 'f_close'.
Case solved -_-

--
Jure
signature.asc
Reply all
Reply to author
Forward
0 new messages