Question about When and Where to use Global Variables

Dumb Questions I have as Always.

Just to clear up a couple of things, I’m not talking about stuff like _G or ModuleScripts, I’m talking about just Regular Variables.

So anyway, What I’m asking is to where use Global Variables, If we are putting this into code, we will have this:

_G.Array = {} -- Deprecated?

Variable = "Привіт Україно!" -- Global Variable (accessible within the Entire script)

local Var = 13 -- Local Variable (accessible within a Scope)

In Luau, It appears people to tend use local when creating Variables, which Looks something like this:

local Integer = 123 -- numbers 
local Text = "Hallo Deutschland!" -- (Auf Deutsch sprechen!)
local Float = 123.456 -- (or "Double," cry about it)

-- people also tend to make the first Letter or a Variable lowercase?
local userData   = {} -- Adding a Space to Line up Variables
local arraytoUse = {} -- ok.
local dogStorage = {} -- not what It sounds
local cashDrawer = {} -- hmmmmmmmmmm...
-- you know, whatever names people have for their stuff

But when adding a Global Within a function, it underlines the Variable and says to use local instead:

function Monaco() -- Whatever Country I could name of the top of my head
    Global = "Hello" -- Underlines?
end)

Are the only uses of a Global Variable just at the Beginning of a Script or outside of any functions?

(Sorry about all the Random stuff I put here, I get “Professional Environment” but still, I want to have fun sometimes)

1 Like

I don’t recommend using global variables for any case. You’d just flood your intellisense environment with many different variables that are usually just used in one scope

2 Likes

Sorry if this is not what you are asking about, but:

When you declare or define a local variable, it sticks to its scope. It won’t overwrite any variables with the same name in outer scopes (this is known as shadowing) and will stop working when you exit that scope:

do
    local x = 9
    print(x) -- 9
end

print(x) -- nil

local y = 8
do
    local y = 17
    print(y) -- 17
end
print(y) -- 8

If you instead define a global variable, it will be accessible later in other scopes:

print(y) -- nil
do
    y = 7 -- 7
end
print(y) -- 7

However, this is very confusing and may cause inadvertent bugs, so it is recommended to at least declare the variable as local to the outermost scope it is useful in, i.e:

do
  do
    local y
    do
      y = 7
    end
    print(y) -- 7
  end
  -- y is not used here.
end

Hope that helps!

3 Likes

yeah…

yoh is cool.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.