Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Can someone explain local and global values to me?

Asked by 9 years ago

I have just now realized I have been using global and local wrong. I always thought it was that tithe locals that can be seen anywhere, not the globals. Can someone please explain this more to me. The ROBLOX wiki doesn't give to much info on them. Thanks. :)

1 answer

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
9 years ago

A global variable is a variable that can be used throughout the entire script.

A local variable is a variable that can only be accessed in the current scope.

It's best to use local variables whenever possible, for it increases readability and efficiency. Even at the top of your script, outside of all scopes, where a local variable would behave the same as a global variable, it's still best to use a local variable because it makes it easier to read.

Scope: Scope is a block of code in which variables are declared. for loops, while loops, repeat until loops, functions, if then, and do end chunks all create a new variable scope. -ROBLOX Wiki

Run the following code and look at your output:

local hi = "Hi!" --Local
bye = "Bye!" --Global

function printVariables() --New scope
    tuba = "Tuba!" --Global
    local violin = "Violin!" --Local

    print(hi)
    print(bye)
    print(tuba)
    print(violin)
end --End of scope

print("STARTING PRINT FUNCTION..")
printVariables()
print("STARTING TO PRINT OUTSIDE OF FUNCTION")
print(hi)
print(bye)
print(tuba)
print(violin)

Here, you'll notice that everything prints fine, because it is all in the global scope, except violin. Violin is a local variable defined in a function. Printing that variable inside the function is fine, because it's in the same scope, but when we try to print it outside of that function, we get an error. This is because local makes it special to that function, or scope, so that outside of that function it simply does not exist.

Ad

Answer this question