2015-06-08 58 views
4

我試圖讓一個計算器成爲一個很好的第一個任務。雖然我有問題io.read函數。io.read被跳過Lua

這裏是我的代碼

io.write("let's try making a calculator in LUA!\n\n") 

io.write("First number?\n> ") 
firstNum = io.read("*n") 

io.write("Second number?\n> ") 
secNum = io.read("*n") 

io.write("Operator?\n>") 
op = io.read() 

--rest of code goes here-- 

它讓我輸入firstNumsecNum,但一旦它到達op一個它只是沒有錯誤退出。這裏的輸出

➜ lua test.lua 
let's try making a calculator in LUA!! 

First number? 
> 10 
Second number? 
> 20 
Operator? 
>⏎ 

任何想法我在做什麼錯在這裏?

+0

使用'firstNum = tonumber(io.read())'讀取具有數的線 –

+2

或'firstnum = io.read(「* n」,「* l」)'。一個簡單的'io.read(「* n」)'留下輸入緩衝區(包括換行符)中的尾隨空白,所以'io.read()'按照需要選取第二個輸入行的其餘部分,而不是第三行。 – siffiejoe

回答

3

原因是,一個數字被讀取,直到您按ENTER鍵。換行符仍在輸入緩衝區中,然後由以下io.read()讀取。

一個選項是讀取op,直到它有效。例如,跳過空白字符:

repeat op = io.read() until op:match "%S" 

,或者僅讀取一個標點字符:

repeat op = io.read() until op:match "%p"