2017-06-20 120 views
0

我試着爲數學方程寫一些簡單的代碼,讀取控制檯輸入。這裏是我最小的可執行例如:從Lua控制檯讀取數字後,如何讀取單詞?

print("Please enter a number") 
local number = io.read("*n") 
print("You entered the number: " .. number) 
print("Please enter 'yes'") 
local word = io.read("*l") 
if word == "yes" then 
    print("Thank you!") 
else 
    print(":(") 
end 

我進入1,壓回,然後進入yes和壓回,但我總是在Lua的控制檯輸出如下:

Please enter a number 
>> 1 
You entered the number: 1 
Please enter 'yes' 
:(

我不明白爲什麼我甚至不能輸入yes。該程序只是終止。 我該如何解決這個問題?

+3

讀一些是有點反直覺在Lua(它讀取一個數字,沒有LF在那之後)。用'io.read(「* n」,「* l」)替換所有'io.read(「* n」)''來修復它 –

回答

1

正如Egor io.read("*n")指出的那樣,將在該數字後面讀取一個沒有換行符的數字。

因此,如果您輸入1並且用io.read("*n")讀取,您實際上會在輸入流中留下空行。

一旦你讀了一個新行io.read("*l") Lua將讀取流中的空行。因此,它不會等待您的輸入,而是立即評估word的內容。由於word是空字符串word == "yes"false

您可以通過使用io.read("*n", "*l")來解決該問題,用於讀取數字和下面的emtpy行。這樣,當你接着調用io.read(「* l」)時,輸入流是空的,Lua將等待你輸入你的單詞。

你可以做運行這段代碼:

print("Enter 1") 
local number, newLine = io.read("*n", "*L") 
print(number == 1) 
print(newLine == "\n") 

要查看你的電話號碼確實是後跟一個"\n"