Getting input from the user in Lua
Asked Answered
A

3

19

How can I get an input from user in Lua (like scanf in C)?
For example, the program ask user his name, then he writes his name, then the program will output his name.

Ajmer answered 22/8, 2012 at 8:29 Comment(0)
I
45

Use io.read() Beware that the function can be customised with different parameters. Here are some examples.

 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

docs:

Ideally answered 22/8, 2012 at 9:40 Comment(0)
T
12

The simplest input can be retrieved using io.read(). This will read a single line from the standard input (usually the keyboard, but can be redirected e.g. from file).

You can use it like this:

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

io.read() is just a shortcut for io.input():read(), similarly io.write() is a shortcut to io.output():write(). See the API for read() here.

Notice that io.write() will not auto-terminate your line like print() does.

Terrel answered 22/8, 2012 at 9:19 Comment(1)
I would suggest using io.stdin:read instead of assuming that the default input file is stdin. Similarly with io.stdout:write.Pianoforte
E
-2
print ('Hello, make a face, ')
local face = io.read()
io.write('Nice, ', face, '!\n')
Euler answered 11/1 at 5:0 Comment(1)
the name is just replaced as a faceEuler

© 2022 - 2024 — McMap. All rights reserved.