What you need to know about Variables!

Yo! Hope everyone is having a great day today, for this tutorial, we’ll be talking about variables, which i touched on just a bit in previous tutorials;
Data Types Tutorial
Referencing and Hierarchy in Roblox | Tutorial

Let’s get started!!

Now what is a variable?
Well a variable holds a value in a reference-able key that is specified by you.

What does that mean???
Well, I can explain it better in script.

local variable = “String”

Now what did I just do here?
First off, I declared the variable as a local variable. This means that I can only reference it inside of the script, or function that I declared it inside.

- -Script
local variable = “String”
print(variable) --[[ -> “String”; See how we can just type the name in as an input? When we run the code, it will find the variable declared and substitute the value we put.]]

--Now, if we declare a function 
local function foo()
--And declare a variable inside here
local newVariable = “Heyy”
print(newVariable, variable) -- -> “String” “Heyy”
--[[This works because our new variable is local to the function, and since we are still inside our function, we can use it, and we are also still inside our current script, so we can still use our original “variable” variable.]]
end --We’re now outside of our function 
print(newVariable) --[[This is invalid, since now we are outside of our function, and we declared it locally to said function]]
print(variable) --Valid; We are still inside our **script**, so our “variable” can still be used. 

Global variables are described without “local” or with the _G.variable, syntax.

This means we can use variables from other scripts, or outside of their declared functions

function foo()
variable = 3
end

foo()
print(variable)
--This prints “3”

Next, I declared my variable name, this can be anything without spaces, with letters, and optionally numbers, and without underscores at the beginning of the variable name. It also cannot only be numbers, and no special characters. [{#%+ etc…

Then, finally I added my value, this can be any of the data types I talked about in my previous tutorial. And they can also be references, like in my first tutorial.

Functions, i didn’t talk about in my last tutorial as data types, but they are also valid data types; I’ll get to functions in my next tutorial.

Let me know if you have any questions, i’ll be happy to help!!

2 Likes

There are more variables such as global variables like this:

--serverscript
_G.variable = "Hello"
shared.variable = "Hey"

--they have to be the same type of script

--new script
print(_G.variable) --not reccomended
print(shared.variable) 
1 Like

Good tutorial, only problem is that is very basic. A bit too basic.


Next time, I recommend you dive a bit deeper, for example, type checking.

Also, both _G & shared are discouraged and you should use ModuleScripts for this. Also, I recommend just stick with local variables, as global variables are discouraged.

2 Likes