Let’s start our first lesson. If you’re new to Lua, one of the first things you’ll want to do is learning how to print out something (the output) and to accept user’s input (the input). This basic I/O is simple but critical for beginners. Just imagine when you are creating a game and want to let your player input their name, or you want to display the results of who are the winner. So now let me walk you through the basic I/O functions in Lua.
Output: Using print()
The simplest form of output in Lua is through the print()
function.
KaClass Team
By using this function, you ask the engine send data to the standard output (usually the terminal or console) which is useful for displaying messages, numbers, or variables.
Coding example on how to use print()
print("Hello, KaClass!") -- Output: Hello, KaClass!
In this example, the string "Hello, KaClass!"
is printed to the screen. Noted that the print()
function automatically adds a newline after the output. So you can try, the next output will appear on a new line.
How to print multiple values? And separating them with commas?
local name = "Alice"
local age = 25
print("Name:", name, "Age:", age) -- Output: Name: Alice Age: 25
In this example, I created two local variables (will be discussed in the next chapter about Lua Variable) and print it out with comma separated. It’s pretty straightforward.
The next example will be similar, but this time we will print out the result of a simple math calculation.
Example: How to print the result of a calculation in Lua?
You can directly use print()
to display the result of an arithmetic operation:
local x = 10
local y = 5
print("Sum:", x + y) -- Output: Sum: 15
Remember to try it out yourself!
Input: Using io.read()
Next, let’s move on to deal with the user’s input. We can simply use the io.read()
function. With the function you can start capture the input from the user. When you try it out in your coding editor and compiler, once your program reaches an io.read()
call, it will wait for the user to type something. And then the user need to press “Enter” before continuing. For sure you can assign the user’s input to a variable for further processing. Let’s see an example below:
How to accept User Input in Lua?
Suppose we want to accept the user’s name and then greets them:
print("What is your name?")
local name = io.read() -- Reads input from the user
print("Hello, " .. name .. "!") -- Output: Hello, [User's Input]!
Thus in this example, the line of code “print("What is your name?")
” prompts the user for input. And then the io.read()
waits for the user to type their actual name and press “Enter”. Finally, the input is stored in the name
variable (Will explain to you what is variable in the next tutorial I promise!)
How to handle different Types of Input?
If you have tried it by yourself, you should notice that by default
reads a line of text (as a string) but sometime you may want to read numbers or specific data formats. What you need to do is passing arguments to io.read()
io.read()
. Let me show you how to do it:
Reading Numbers: If you expect the user to input a number, use "*n"
as an argument for
. By passing this argument, Lua will treat the input as a number, i.e.io.read()
print("Enter a number:")
local number = io.read("*n") -- Reads a number
print("You entered the number:", number)
Reading a Single Line: If you want to read a single line, use io.read("*l")
will make it.
Reading Until the End of File: Using io.read("*a")
can reads the entire input until the end of the file (or input stream). This is useful for reading large chunks of text when dealing with file handling. We will go deep into Lua I/O file handling in the later chapter. You may jump into this here: File I/O.
Example: Adding Two Numbers (Input) and Print (Output)
Now let’s combine what we have learned so far with the following example
print("Enter the first number:")
local num1 = io.read("*n") -- Read the first number
print("Enter the second number:")
local num2 = io.read("*n") -- Read the second number
local sum = num1 + num2
print("The sum is:", sum)
In this Lua program, we asks the user for two numbers using io.read("*n")
. And then we adds the numbers and displays the result using print()
. Let’s try it yourself with different parameters!
How to check if the user’s Input Correctly?
Sometime you may not get what you expected from the user input. Handling error is one of the key process in programming. Since
expects certain types of input, it’s really important to validate the user input types (For data type we will discuss into details coming chapters). io.read()
For example, if you expect a number but the user types a string, what will happen?
Lua will throw an error.
That’s not a good thing. So you can use basic error checking design to make sure the program handles invalid input gracefully. In below example, I do it by checking if the input is a valid number with if-then-else (you can find it out what is Lua Condition Checking here)
print("Enter a number please:")
local input = io.read()
local number = tonumber(input)
if number then
print("You entered the number:", number)
else
print("Invalid input! Please enter a valid number.")
end
Here, tonumber()
converts the input into a number if it’s valid. Intuitively, it returns nil
if there are something wrong. So the program can handle the invalid input accordingly.
Simple Interactive Lua Program like “Chatbot”
Now let’s make it more fun and build a slightly more interactive “chatbot” example. Sure it’s NOT an AI chatbot but just combining what we have learned so far about input and output. This simple program try to asks the user for their name and age. Next the Lua program tells them how old they’ll be in five years.
print("What is your name?")
local name = io.read()
print("How old are you?")
local age = io.read("*n") -- Read age as a number
local future_age = age + 5
print("Hello, " .. name .. "! In five years, you will be " .. future_age .. " years old.")
Noted that the program prompts the user for their name using io.read()
. After capture the input as a string, it then asks for the user’s age using io.read("*n")
to ensure the input is treated as a number. Finally, the Lua program calculates the user’s future age, then print it out as a friendly message. You can modify it to make it more interesting!
Conclusion
To wrap it up, understanding standard Input and Output in Lua scripting are very important. it allow you to make the Lua programs more interactive. With print()
for output and io.read()
for input, you can create engaging scripts which can easily interact with other players. I hope you found these functions are easy to learn. I put it at the beginning is to make sure you master this very first steps before dealing with coming Lua programming challenge. Feel free to experiment by yourself for different types of data. Some students can start to create simple calculators, quizzes, or small text-based games after this chapter. See you in the next one!