đź§  Luau Basics: Variables

Variables are one of the most important concepts in programming. They allow us to store, update, and reuse values in our code.

📦 What is a Variable?

A variable is a named storage location that holds a value or a reference to a value.

You can use it to remember things like a player’s score, a player’s name, the time of day, references to other objects, and much more!

We can retrieve these variables and access the values stored inside of them, so think of them like labelled cardboard boxes in your home that you can put stuff in and take stuff out.

The following code below will be executed line-by-line from top to bottom, initializing each variable, and then printing the value stored in score:

score = 100
playerName = "Alex"
timeOfDay = "12:00 PM"
spawnLocation = workspace.SpawnLocation
print(score) -- '100'

Program State

Variables are building blocks for the state of your scripts.

100 represents the current state of score, but at some point in the future, the value of score could change, which reflects a new state of your code at that time.

Multi-Line Declaration

You can even declare multiple variables on the same line using multiple assignment.

You just need to separate the names and values by commas:

score, health, age = 500, 100, 25
print(score, health, age) -- 500, 100, 25

Changing a Variable

You can update a variable by assigning it a new value using the assignment (=) operator.

health = 100
print(health) -- 100
health = 80 -- assigned a new value to 'health'
print(health) -- 80

Naming Conventions

You may have noticed that we named our variables in a particular way in the previous code blocks.

The most common naming convention is called camelCase, whose rule is that the first word must be lowercase while every subsequent word must have their first letter capitalized!

There are many other common naming conventions in the programming world:

  • ThisIsCalledPascalCase
  • this_is_called_snake_case
  • THIS_IS_LOUD_SNAKE_CASE

Each naming convention is unique for a particular situation. For example, loud snake case is used to represent a variable as being constant, meaning its value should never change.

Other programming languages have the ability to define constants (such as const in C++), but Luau does not have this feature.

To work around this, we name constants differently to communicate to the programmer its value should never change during runtime.

Naming Tips

When we practice more with variables, it’s best to make sure that your variable names are clear, descriptive, and direct as possible.

Use Positive Form

It’s good practice to make sure variable names are in positive form.

Here are a couple examples:1

  • wasCalled is better than hasBeenCalled (more direct)
  • isFlying is better than isNotFlying (positive form)
  • late is better than notOnTime (more direct and positive form)

Variables also have a few rules regarding their names:

  • You cannot name variables starting with numbers
  • They cannot contain special characters (except for underscore)
  • You cannot use any of the reserved keywords in Luau

Here are a few examples of invalid variable names:

  • 50dogs
  • myVar!
  • end (reserved keyword)

Here are a few examples of valid variable names:

  • _myVar
  • the_end
  • countingTo100

Naming is a skill!

As you write code, read other developer code, and build projects, you’ll naturally grow your ability to properly name variables.

Naming things can be considered one of the hardest things to do in computer science.

If you have free time, check out this awesome video:

Comments

Comments are notes you leave in your code that Luau ignores.

They help communicate to you and other developers what your code does, but more importantly, why the code does it.

We’ll take a peek at some basic comment syntax and explore them richly in a future lecture.

Single-Line Comments

Use two dashes (--) for single-line comments:

-- This is a comment
score = 100 -- This is an inline comment

Multi-Line Comments

Use --[[ and ]] for multi-line comments:

--[[
This is a multi-line comment.
It can span multiple lines!
...forever!
]]

Luau Data Types

There are currently ten built-in data types in Luau:2

Data TypeDescription
nilRepresents the absence of a value
stringRepresents text ("hello", "crusherfire", etc.)
numberAll numbers (1, -100, 0.314, etc.) stored as a double
booleantrue or false
tableData structure that can hold other values
functionA reusable block of code
threadAlso known as a coroutine, this represents an execution context that can be paused and resumed for multi-tasking purposes
userdataA host-provided object (Roblox data types such as Instance, Part, Color3, etc.)
vectorRepresents a mathematical vector
bufferA mutable block of memory for data compression and serialization

The vector and buffer data types are also exclusive to Luau and do not exist in standard Lua.

The fundamental data types we’ll be prioritizing over the next few lectures will be nil, string, number, boolean, table, function, and thread.

The other data types will be explored more in the future, so do not worry about them for now!

type

type is a global function that you can call to determine the type of a given value returned as a string.

This is a useful function for identifying the types of values, and we’ll utilize this function more in the future:

TypesExample
myValue = 10
valueType = type(myValue)
print(valueType) -- "number"
myValue = true
valueType = type(myValue)
print(valueType) -- "boolean"
myValue = { 1, 2, 3 }
valueType = type(myValue)
print(valueType) -- "table"

Practice Activities

What will the following code print into the console?

myValue = nil
valueType = type(myValue)
print(valueType)

What will the following code print into the console?

myValue = "Hello, world!"
valueType = type(myValue)
print(valueType)

typeof

typeof is another global function that is extremely similar to type but is specifically built for the Roblox game engine.

This function is useful for further refining Roblox data types specific to the game engine and not the Luau language itself.

We’ll see this function used in the future.

Storing Object References

Since learning about indexing for instances, we can store object references in variables and use them for later, which is an extremely common pattern you’ll perform constantly.

Lighting = game:GetService("Lighting")
spawnLocation = workspace.SpawnLocation
print(spawnLocation.ClassName) -- "SpawnLocation"
print(spawnLocation.Parent) -- Workspace
print(Lighting.Ambient) -- 0.27451, 0.27451, 0.27451
print(Lighting.Brightness) -- 3

🎯 Practice Activity

Going to back to our first practice activities that we attempted in a previous lecture for indexing instances, I’d like for you to update your code to store the instances in variables before printing them.

Setup

  1. Create a new Script in ServerScriptService
  2. Set the script’s name to "VariablesPractice"
  3. Script the instructions step-by-step

Goal

  1. Store the Terrain, SpawnLocation, and Baseplate into variables
  2. Print any three properties for each instance
  3. Run the game and ensure your prints appear in the output

Tip

When you write the code, notice how you can keep referencing your newly created variables instead of having to constantly re-index the workspace to access your desired object.

Bonus Challenge

Along with printing the values of the properties, utilize the type function to also print the types of the values.

If any of the properties you print display as userdata, then try to further refine the type using typeof instead!

Solution


âś… Key Takeaways

  • Variables store state.
    • They represent values in memory that describe what your program knows right now. When a variable changes, the state of your code changes.
  • Assignment = sets or updates values.
    • You can use it to initialize a variable or reassign it later to reflect new information.
  • Variables are read top-to-bottom.
    • Code executes line-by-line, so the order you declare and change variables matters.
  • Clear naming is better than clever naming.
    • Descriptive, positive, and consistent names makes your code easier to read and maintain.
  • Naming conventions communicate intent.
    • Styles like camelCase, PascalCase, and LOUD_SNAKE_CASE help signal how a variable should be used.
  • Comments explain why, not just what.
    • Use comments to clarify intent, assumptions, and reasoning that is not obvious from the code itself.
  • Every value has a type!
    • Luau uses different data types to represent different kinds of values, and understanding these types is foundational for writing correct logic.
  • type & typeof are your inspection tools.
    • When you are unsure what kind of value you are working with, type/typeof helps you verify.

The Big Picture

Variables are the foundation of everything that follows in this course. Conditionals, loops, functions, systems, and game logic all rely on storing and updating values.

Mastering variables early will make every future concept easier to understand and reason about!

Footnotes

  1. https://gist.github.com/evaera/fee751d4e228dd262fe1174ba142a719 ↩

  2. https://luau.org/typecheck#builtin-types ↩