lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Sam Roberts writes:
>  io.stdin:close()
>  loadfile() -- load stdin
> What exactly did the caller expect this code would do?

I expected loadfile() to fail, returning something like (nil, "cannot read
stdin: file closed").  After all, io.stdin:read("*a") raises an error "attempt
to use a closed file".  However, as noted, the Lua 5.1.2 loadfile() may succeed
and have some strange side-effects if an unrelated io.open is placed before it.

Sam Roberts writes:
> Core and io are both using stdin, but they don't cooperate,
> otherwise loadfile() would use io.stdin, and all would be well again.

I agree, if loadfile accessed the Lua file object (io.stdin) rather than the C
stdin directly, then loadfile could properly check whether io.stdin is closed
and return an error, just like file:read does.  (I suppose this abstraction
could conceivably even allow io.stdin to be different from C stdin.)

The bug originally surfaced in a Win32 GUI app embedding Lua.  C stdin was a
null device, and I thought it would be helpful to the user to io.stdin:close()
so that all attempts to access io.stdin would result in a visible error.  That
seemed to work initially, but there was later found this lurking bug in the
loadfile behavior.

Preventing io.stdin:close() in the first place, as Roberto notes, would also
have been sufficient (but not necessary?) to avoid the problem.

Something that should also be considered is if C code does a fclose(stdin)
before (or after) starting up a Lua instance.  Lua 5.1.2 assumes that stdin is
open.  Closing C stdin from C and then doing a print(io.stdin) in Lua still
results in something like "file (0x61101080)" rather than "file (closed)", and
attempts to operate on the object might be invoking undefined behavior.  If Lua
cannot detect automatically that C stdin is closed, then it would be proper for
the C program to somehow notify Lua of this by some standard mechanism.