【发布时间】:2012-08-17 15:21:04
【问题描述】:
如何在 Lua 中获取用户的输入(例如 C 中的 scanf)?
例如,程序询问用户姓名,然后他写下他的姓名,然后程序将输出他的姓名。
【问题讨论】:
如何在 Lua 中获取用户的输入(例如 C 中的 scanf)?
例如,程序询问用户姓名,然后他写下他的姓名,然后程序将输出他的姓名。
【问题讨论】:
使用 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
【讨论】:
可以使用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() 那样自动终止您的线路。
【讨论】:
io.stdin:read,而不是假设默认输入文件是stdin。与io.stdout:write类似。