xirishpvp
xirishpvp

Reputation: 21

standard input file is closed stack traceback error when looping a function to open a file in lua

1local function readfile(name)
2    io.input(name)
3    local file = io.read("*all")
4    io.close(io.input())
5    return(file)
6end
31repeat
32   local input = io.read()
33  if string.sub(input, 1, 1) == ("@") then do
34    local ninput = string.sub(input, 2, 100)
35    print(readfile(ninput))
36  end
37end
38until input == ("stop")

i get this error every time i try to run the code. it runs once then errors out afterward and help is much apreciated.

lua:32: standard input file is closed
stack traceback:
        [C]: in function 'io.read'
        testing.lua:32: in main chunk
        [C]: in ?

Upvotes: 1

Views: 174

Answers (1)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23767

Read files with io.open to avoid touching stdin.

local function readfile(name)
    local f = assert(io.open(name))
    local content = f:read("*all")
    f:close()
    return content
end

Upvotes: 1

Related Questions