2012-08-22 87 views
5

如何從Lua中的用戶獲取輸入(如C中的scanf)?
例如,程序詢問用戶他的名字,然後他寫下他的名字,然後程序會輸出他的名字。從Lua中的用戶獲取輸入

回答

15

使用io.read()注意可以使用不同的參數來定製該功能。這裏有些例子。

s = io.read("*n") -- read a number 
s = io.read("*l") -- read a line (default when no parameter is given) 
s = io.read("*a") -- read the complete stdin 
s = io.read(7) -- read 7 characters from stdin 
x,y = io.read(7,12) -- read 7 and 12 characters from stdin and assign them to x and y 
a,b = io.read("*n","*n") -- read two numbers and assign them to a and b 
4

最簡單的輸入可以使用io.read()來檢索。這將從標準輸入中讀取一行(通常是鍵盤,但可以從文件重定向)。

您可以使用它像這樣:

io.write('Hello, what is your name? ') 
local name = io.read() 
io.write('Nice to meet you, ', name, '!\n') 

io.read()僅僅是io.input():read()一個快捷方式,同樣io.write()是一個捷徑io.output():write()See the API for read() here

請注意,io.write()不會像print()那樣自動終止您的行。

+3

我會建議使用'io.stdin:read'而不是假定默認輸入文件是'stdin'。與'io.stdout:write'類似。 –