So I understand global and local variables, but if I do this
local function a() b = 5 end print(b) --prints nil
b doesn't have a local before it, but it isn't available outside of the function. Does that mean that variables that are declared inside of a function, even if they don't have a local before them, are local?
You have just defined the function telling it what to do, but you never called the function. Also yes, it is a global variable. Functions never run automatically, you have to call them your self. Once you tell the function what to do, call it so that it executes.
local function a() b = 5 end a() -- Calls the function print(b) --prints 5
So local variables are variables that are local to the function. Global Variables are variables that can be used in multiple functions in the script.
So in this example:
local GlobalVariableNameBlah local function RandomFunctionName() local LocalVariableNameBlah end
GlobalVariableNameBlah is a global variable and can be changed from anywhere in the script. However LocalVariableNameBlah is only alive as long as the function is running. And only things inside that function can access that variable.
So for example:
If I wanted to change the Global Variables value I could do it inside the function. Also note that I could have made it a string or a bool. I just chose an integer.
local GlobalVariableNameBlah local function RandomFunctionName() local LocalVariableNameBlah GlobalVariableNameBlah = 20 end
I can't change the Local variable outside of this function in another function. So for example
local GlobalVariableNameBlah local function RandomFunctionName() local LocalVariableNameBlah GlobalVariableNameBlah = 20 end local function OtherFunctionName() -- This would be wrong because it only exists in RandomFunctionName -- And is deleted as soon as the RandomFunctionName ends. -- This would crash it. LocalVariableNameBlah = 20 -- I can call the global variable though GlobalVariableNameBlah = 30 end
It's also important to note that these functions would not run unless I say below them
RandomFunctionName() OtherFunctionName()
If they were non local functionsI could call them above them like so:
local GlobalVariableNameBlah RandomFunctionName() OtherFunctionName() function RandomFunctionName() local LocalVariableNameBlah GlobalVariableNameBlah = 20 end function OtherFunctionName() -- This would be wrong because it only exists in RandomFunctionName -- And is deleted as soon as the RandomFunctionName ends. LocalVariableNameBlah = 20 -- I can call the global variable though GlobalVariableNameBlah = 30 end
Anything declared inside a function is local yes. Hope this answered your question.