Luau
Variables

Variables

Variables are like a box with a name, and inside of this box, you can store a number, some text, or any piece of information.

Defining variables

local myFavoriteNumber = 7
print(myFavoriteNumber)

Try running this code, this code should print "7" to the output.

The above code tells the computer that from now on, there is a variable named myFavoriteNumber, and its initial value is 7.

This is called defining a variable, defining a variable is done by typing local followed by the name of the variable, also known as the identifier. Then an equal sign (=) followed by the initial value of the variable.

local identifier = initialValue

An identifier can only contain lowercase and uppercase letters from A-Z, digits from 0-9 and underscores (_), it can also not start with a number, meaning 0foo is invalid.

After defining the variable, you can refer to this variable using the name of the variable, you can then use this and pass it to functions or do math with it.

What does local mean?

local is used to specify that the variable is a local variable, meaning it is scoped. We will learn more about Scoping in the future.

Assigning Variables

local myFavoriteNumber = 7
print(myFavoriteNumber) -- prints "7"
 
myFavoriteNumber = 5
print(myFavoriteNumber) -- prints "5"

This code should print 7, followed by a 5. We're changing the value of this variable to 5.

This is known as an assignment, we're assigning or setting the variable to 5.

Uninitialized Variables

You could also define a variable which doesn't have an initial value.

local foo
print(foo) -- prints "nil"
 
foo = 5
print(foo) -- prints "5"

Coding Challenge

Create a variable named foo initialized with the value "Bob" and print the variable foo. Then, assign variable foo to "Alice" and print the variable foo.

Expected Output
Bob
Alice