So I have had this question that popped up into my mind this morning, and I would just like to ask it,
Do I need to be using local variables more and should I stop using global variables and only use local variables? From a lot of the scripts that I have seen on the dev forum, almost none of them use global variables. Is there even a point in using global variables? Thanks for helping me out
You should always be using local variables unless the situation requires it (which is quite rare). Local variables have a slightly lower performance footprint too, so your game will be a tiny bit faster. There aren’t many cases that require a global variable:
If you have a variable in a function that needs to be accessed later then either use return or define the variable outside of the function.
If you have a variable in an if statement then that too can be avoided by defining a variable beforehand.
A couple of tips with variables:
When defining a variable you don’t always have to have a value if you are changing it later - you can just use local Variable with no =.
You can define multiple variables by doing local VarOne, VarTwo = 1, "Two".
There is pretty much no point in using global variables as i’m pretty sure you will never need them. You can do everything and more with a local variable rather than a global one.
No problem! Always good to ask questions. Basically, what I’m saying is that you can create a variable - but it doesn’t have to have a value. For example:
local Number
print(Number)
Number = 1
print(Number)
The first part will print nil because there is no value assigned to Number. The second part will print 1 because there is now a value for Number.
PS: If my original post was helpful, consider marking it as the solution.
oh yh, I see, now I understand this a little better, thank you for helping me, I really appreciate it, the dev forum is actually helping me a lot to understand scripting a lot better. Thanks so much!!!