在 Lua 中获取用户输入

问题描述 投票:0回答:3

如何在 Lua 中获取用户的输入(如 C 中的

scanf
)?
例如,程序询问用户他的名字,然后他写下他的名字,然后程序就会输出他的名字。

input lua
3个回答
43
投票

使用 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

11
投票

可以使用

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()
的快捷方式。 请参阅此处
read()
的API

请注意,

io.write()
不会像
print()
那样自动终止您的线路。


0
投票

print ('你好,做个鬼脸,') 本地人脸 = io.read() io.write('不错,',脸,'! ')

© www.soinside.com 2019 - 2024. All rights reserved.