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. :)
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.