file-io - 从文件读取后的命令行输入

标签 file-io lua user-input

您好,我正在尝试读取包含单词列表的文件,然后让用户在命令行上输入一个数字来选择他的单词。但是,当我运行代码时,它不允许我输入数字。这是我的代码:

function readFile(file)

     array = {}
     io.input(file)
     line = io.read()
     table.insert(array, line)

     while true do
           line = io.read()
           if line == nil then break end
           table.insert(array, line)
     end

     length = #array
     count = 1

     while count <= length do
           print(count .. ". " .. array[count])
           count = count + 1
     end

     return array

end

function chooseWord(wordArr)

     local answer
     io.write("Select a Number to choose a word")
     answer = io.read()
     local word = wordArr[answer]
     print(word)

     return word
end


words = readFile("dictionary.txt")
word = chooseWord(words)

如果我删除 readFile 函数,我可以完美地输入,但是一旦我读取了文件,我就可以了

最佳答案

更好的使用:

local f = io.open(file, "r")
line = f:read()
f:close()

等等

在您的情况下,您将标准输入文件(使用 io.input)从 stdin 更改为您的文件,然后您必须重置它。但这不是一个好的解决方案

关于file-io - 从文件读取后的命令行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120958/

相关文章:

javascript - 加载时显示输入文件对话框?

java - ProcessBuilder 最后执行

java - 我在 defaultWriteObject 处收到 NotActiveException,但我不知道为什么

string - Lua:在分隔字符串中查找标记

java - 如何让GUI等待用户输入?

java - 如何使用 token 拆分用户的输入?

c# - 发送电子邮件后删除文件时出现 "process cannot access file"错误

c++ - tolua++ 忽略赋值和不等运算符?

time - Lua - 当前时间(以毫秒为单位)

java - 用户输入无法解析