Input

Objective

After working through this lesson, you'll be able to:

  • Ask the user for input

  • Print values

  • Store user input in variables

input with io.read()

io.read() reads a line from the standard input.

Typically, you'll want to assign a variable to input.

print("What's your name? ")
name = io.read()
print("My name is " .. name)

By default, io.read() reads in a string.

input number

If you want the input to be a number, use io.read("*number")

print("Give me a number: ")
num = io.read("*number")

output with io.write()

As a rule, you should use print for quick-and-dirty programs, or for debugging and io.write() when you need full control of your output.

Unlike print, io.write() adds no extra characters to the output, such as tabs or newlines.

io.write("Please enter your name: ")
name = io.read()
io.write("Hello ", name)

Notice, unlike the print function, io.write() does not add a new line to the output.

Avoid using concatenation

Avoid code like io.write(a..b..c)

The call io.write(a,b,c) accomplishes the same effect with fewer resources as it avoids string concatenation.