Search code examples
lua

Unable to use io.read() to grab the user's input after already using it to grab a file's contents


I've got this program that starts off with the program grabbing a file's contents.

local oldprint = print
local print = io.write
-- this was done mainly because the newline from print() wasn't needed

io.input("script.txt")

local script = io.read("*all")

io.close()

Then there is a function containing another io.read(), which should allow for the user's input.

local functions = {
    [","] = function()
        local input
        repeat
            print("\nAwaiting input... (must be a number)\n")
            input = io.read("*n")
        until input ~= nil
        array[pointer] = input
        print(stringy)
    end
}

functions[","]()

I expect it for it to print once, and then grab the input, but it ends up constantly printing.

I've tried using io.flush(), but it didn't work, and I'm not exactly sure what else to try...


Solution

  • By calling io.input("script.txt") you set that file as the default input file. Any following calls to io.read() will hence read from that file.

    Either use file:read instead of io.read or reset the input to the standard input stream by calling io.input(io.stdin).

    I suggest you refer to the Lua reference manual.

    https://www.lua.org/manual/5.4/manual.html#6.8