Lua Variable Tutorial – Complete Guide

Ever wondered how to give different parts of your game functionality and interactivity? One of the keys to doing so lies in the use of variables in coding. This feature, commonly found in many game creation platforms, enables you to create stunning digital experiences that react to user input. One such language for managing the behavior of game elements is Lua, a lightweight, compact scripting language often realized in the gaming universe.

What are Lua variables?

In the Lua scripting language, variables are essentially named storage locations to hold different types of values. They allow us to store, modify, and access data throughout our code. There are different types of Lua variables, such as global, local, and table variables, each with their own unique applications and scope.

Why should I learn about Lua variables?

The use of variables is fundamental to virtually any programming language, and Lua is no exception. These powerful programming tools allow you to create dynamic and interactive games. Without variables, your game elements would be static and non-interactive. In Lua, understanding variables is not only crucial to manipulate game behaviors but also enhances the efficiency and readability of your code, speeding up the development process.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Working with Lua Variables: Basics

Let’s start by exploring basic variable assignment. Variables in Lua are dynamically typed, meaning the type of value a variable can hold is not fixed.

-- Variable assignment in Lua
myVariable = 10
print(myVariable)  -- Outputs: 10

To assign a different type of value to the same variable, we simply repeat the process:

-- Variable reassignment in Lua
myVariable = "Zenva Academy"
print(myVariable)  -- Outputs: Zenva Academy

Scope of Lua Variables

As mentioned, Lua has different types of variables based on their scope: global and local. If a variable is not explicitly declared as local, it’s considered global by default and can be accessed anywhere in your batch of code. Here is how we declare a global variable:

-- Global variable declaration
globalVariable = 20
print(globalVariable)  -- Outputs: 20

On the other hand, local variables can only be accessed within the block of code or function in which they were declared. Local variables are characterized with the keyword ‘local’ during the declaration:

-- Local variable declaration
local localVar = "Learn at Zenva!"
print(localVar)  -- Outputs: Learn at Zenva!

Nil Value in Lua

When a variable is declared in Lua and no value is assigned, its default value is nil. This can also be used to delete a variable:

-- <a href="https://gamedevacademy.org/lua-nil-tutorial-complete-guide/" title="Lua Nil Tutorial – Complete Guide" target="_blank" rel="noopener">nil usage in Lua</a>
freshVariable = nil
print(freshVariable)  -- Outputs: nil

Once a variable is given a nil value it behaves as if it was never declared.

-- Deleting a variable using nil
globalVariable = nil
print(globalVariable)  -- Outputs: nil

Understanding Lua Variable Types

In Lua, variables don’t have types. Instead, it’s the values that have types. Here are some of the more common types that Lua variables can store:

  • Numbers: Lua can handle both integers and floating-point (decimal) numbers.
  • Strings: Text data in Lua is usually stored as strings.
  • Booleans: Boolean values represent true or false conditions.
  • Tables: Table is Lua’s sole data structuring mechanism. They can be used to represent ordinary arrays, lists, sets, records, queues, and other data structures in a simple, uniform, and efficient way.

Let’s illustrate these types with some example code:

Numbers

-- <a href="https://gamedevacademy.org/lua-number-tutorial-complete-guide/" title="Lua Number Tutorial – Complete Guide" target="_blank" rel="noopener">Numbers in Lua</a>
local integer = 10
local float = 92.5
print(integer)  -- Outputs: 10
print(float)  -- Outputs: 92.5

Strings

-- <a href="https://gamedevacademy.org/lua-string-library-tutorial-complete-guide/" title="Lua String Library Tutorial – Complete Guide" target="_blank" rel="noopener">Strings in Lua</a>
local website = "https://academy.zenva.com/"
print(website)  -- Outputs: https://academy.zenva.com/

Booleans

-- <a href="https://gamedevacademy.org/lua-boolean-tutorial-complete-guide/" title="Lua Boolean Tutorial – Complete Guide" target="_blank" rel="noopener">Boolean in Lua</a>
local isLearning = true
print(isLearning)  --Outputs: true

Tables

Defining tables and accessing data stored in tables is accomplished in the following manner:

-- Tables in Lua
local students = {"Alice", "Bob", "Charlie"}
print(students[1])  -- Outputs: Alice

As shown in the above example, table indices in Lua start from 1, not 0 as in many other programming languages.

Adding to and Removing From Tables

As Lua tables are dynamic, we can add to and remove from them effortlessly. Let’s see an example:

-- Adding to <a href="https://gamedevacademy.org/lua-table-tutorial-complete-guide/" title="Lua Table Tutorial – Complete Guide" target="_blank" rel="noopener">Lua table</a>
table.insert(students, "David")
print(students[4])  -- Outputs: David

-- Removing from Lua table
table.remove(students, 1)
print(students[1])  -- Outputs: Bob

These are just few of the basic operations that you can perform on Lua variables. Remember, deep understanding of variables and their capabilities is paramount in mastering a programming language. Happy Coding!

Manipulating Strings in Lua

Beyond simple assignment and printing, we often need to manipulate strings in various ways. Lua provides several string manipulation functions that you can use to perform operations like concatenation, finding the length of a string, and so on.

Take a look at some examples:

Concatenation

In Lua, we use the “..” operator to concatenate (join together) two strings:

-- String concatenation in Lua
local string1 = "Hello, "
local string2 = "World!"
local greeting = string1..string2
print(greeting)  -- Outputs: Hello, World!

Finding Length

We can find the length of a string in Lua using the ‘#’ operator:

-- Finding string length in Lua
local stringLength = #"Zenva Academy"
print(stringLength)  -- Outputs: 12

Conditional Statements in Lua

Conditional statements help us control the flow of our Lua programs. With them, we can run code blocks conditionally based on boolean expressions. Here’s a simple example:

-- Conditional Statement in Lua
if true then
    print("This will always print")
end

if false then
    print("This will never print")
end

Loops in Lua

Loops are another essential control structure in Lua. They allow us to repeatedly execute a block of code. Below are some of the loops you can use in Lua:

While Loop

A while loop in Lua will continue running as long as a certain condition is met:

-- While loop in Lua
local i = 0
while i < 5 do
    print(i)
    i = i + 1
end

For Loop

A for loop in Lua executes a block of code a specified number of times:

-- For loop in Lua
for i = 0, 5 do
    print(i)
end

Functions in Lua

Functions are reusable blocks of code that perform a specific task. Here’s how you define and call a function in Lua:

-- Defining a Function in Lua
function sayHello()
    print("Hello, Zenva")
end

-- Calling a Function in Lua
sayHello()  -- Outputs: Hello, Zenva

Where to go next?

Now that you’ve made it through this introduction to Lua variables, you’re probably thinking about where to go next on your coding journey. We encourage you to keep honing and applying your skills to increasingly complex projects. Practice makes perfect, and there’s no better way to learn than by doing.

If you’re interested in game development, a great next step could be to check out our Roblox Game Development Mini-Degree at Zenva Academy. This comprehensive selection of courses covers game creation using Roblox Studio and Lua. The Courses dive into the foundations of Roblox Studio, level designs, multiplayer combat, leaderboards, and more, suitable for both beginners and experienced developers. This makes for an excellent learning opportunity, as you’ll get to deep dive into game development using Lua.

Alternatively, if seeking a broader collection of courses, visit our Roblox page. With our flexible, project-based and beginner to professional level courses, you’re not limited by your current skill level, and there’s definitely something for everyone at Zenva. Happy learning, and we look forward to being a part of your coding journey!

Conclusion

Getting to grips with variables in Lua opens up a whole world of possibility when it comes to creating exciting and interactive games. With just a bit of practice and creativity, you can utilize the concepts you’ve learnt in this tutorial to fashion incredible virtual experiences.

Remember, the key to becoming a successful game developer, like any skill, lies in consistent learning, practice and iteration. So why stop here? Dive deeper into the fantastic world of game development with our Roblox Game Development Mini-Degree and turn your game ideas into reality. After all, the best way to learn game development is by making games. Let’s get coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.