Now that you have written your first Lua program and learned how to display messages using the print function, it’s time to take the next step. In this lesson, you will discover how to store and use information in your programs using variables. This is a key concept in all programming languages, and it will help you make your Lua scripts much more powerful and flexible.
A variable is like a labeled box where you can store data, such as a word, a number, or even more complex information. In Lua, you can create a variable using the local keyword, give it a name, and assign it a value. For example, if you want to store your travel destination, you can write:
You can then use the print function to display the value stored in your variable:
When you run this code, Lua will show the word Paris in the output. This is because the variable destination holds the value "Paris", and print(destination) tells Lua to display it.
Output:
Variable names in Lua are case sensitive. This means that destination, Destination, and DESTINATION are all considered different variables. For example, if you try to print Destination instead of destination, you will not see an error, but Lua will print nil because Destination has not been defined:
In Lua, the name you give to a variable is called an identifier. Identifiers are used to label and refer to your variables throughout your code. There are a few simple rules to follow when creating identifiers in Lua:
- An identifier must start with a letter (a–z or A–Z) or an underscore (
_). - After the first character, you can use letters, numbers (0–9), or underscores.
- Identifiers are case sensitive. For example,
scoreandScoreare different variables. - You cannot use spaces or special characters (like
!,@,#, etc.) in identifiers. - Identifiers cannot be the same as Lua’s reserved keywords (such as
local,if,end, etc.).
Here are some examples of valid and invalid identifiers:
Choosing clear and descriptive identifiers makes your code easier to read and understand. For example, use destination instead of just d if you want to store a travel destination.
Variables are essential because they let you store, update, and reuse information throughout your program. Imagine planning a trip: you might want to keep track of your destination, the number of days you’ll stay, or the total cost. With variables, you can easily manage all this data and make your programs interactive and dynamic.
Learning how to use variables is a big step forward in your programming journey. It opens the door to creating more interesting and useful Lua scripts. Are you ready to give it a try? Let’s move on to the practice section and start working with variables!
