How to use variables in your game!

This tutorial will show you the basics of variables.

by Kcdog9

Author Avatar

Lets start by creating a variable. To do this you have to use local.

local NameOfVariable = nil

Nil means nothing or empty. Now we need to come up with a name for our variable. This shouldn't take to long. For example, I'll name my variable Hotdogs.

local Hotdogs = 3

Types of variables

Variables can be used in multiple ways. In a string form, number form, boolean, or nil. A string has to be used in quotes.

local Hotdogs = "three" --String value (has to be used in quotes)

local Hotdogs = 3 --Number value (most common)

local Hotdogs = true --Boolean value (true or false)

local Hotdogs = {} --Table (used to store multiple values in one variable)

Changing Variables

We have our variable but now we want it to change. To do this you will need to input the name of the variable into your code and use the = sign to change it to any value. (It can be a different type) We are going to use the wait() function so it doesn't change right away. I am also going to make it a bit more "intresting" by adding math into the code.

local Burgers = 6
local Hotdogs = 3
Hotdogs = Hotdogs + Burgers --Hotdogs + Burgers = 9
Burgers = Hotdogs - Burgers --Hotdogs - Burgers = 3
print(Hotdogs + Burgers) --Hotdogs + Burgers = 12

Lets summarize this code. Burgers = 6 and Hotdogs = 3. It waits 5 seconds. Then Hotdogs becomes 9 because 3 (Hotdogs) + 6 (Burgers) = 9. Then Burgers becomes 3 because 9 (Hotdogs) - 6 (Burgers) = 3. Then the code prints 12 because 9 (Hotdogs) + 3 (Burgers) = 12. What if the lines where we switched the variables were switched around?

local Burgers = 6
local Hotdogs = 3
Burgers = Hotdogs - Burgers --Hotdogs - Burgers = -3
Hotdogs = Hotdogs + Burgers --Hotdogs + Burgers = 0
print(Hotdogs + Burgers) -- negative 3 + 0 = -3

Instead of 12 being printed, -3 was printed. Remember, order ALWAYS matters when doing math. Another tutorial will be made for math soon.

Making it do something

We changed the variable but right now it doesn't do anything. Lets try printing it in the output. When printing a variable you do not have to use quotes. You can just simply put the name of the variable inside the print function.

local Hotdogs = 3
Hotdogs = "three"

View in-game to comment, award, and more!