在Lua中获取用户的输入

oiy*_*yio 9 lua input

如何在Lua中获得用户的输入(如scanf在C中)?
例如,程序询问用户他的名字,然后他写下他的名字,然后程序将输出他的名字.

hen*_*rik 25

使用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
Run Code Online (Sandbox Code Playgroud)


Mic*_*man 7

可以使用检索最简单的输入io.read().这将从标准输入读取一行(通常是键盘,但可以重定向,例如从文件中).

你可以像这样使用它:

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

io.read()只是一个捷径io.input():read(),同样io.write()是一个快捷方式io.output():write().请在read()此处查看API.

请注意,io.write()不会像您那样自动终止您的行print().

  • 我建议使用`io.stdin:read`而不是假设默认输入文件是`stdin`.与`io.stdout:write`类似. (5认同)