2015-12-06 42 views
2

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

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功能我可以输入完全正常,但一旦我读的文件,我

回答

2

更好地利用:

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

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

+0

太棒了!谢谢! – user2525608