Should I be using Local Variable more

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

Have a wonderful day!!!

1 Like

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".
6 Likes

what do you mean by this? sorry I am quite new to scripting, could you please explain what this means if you don’t mid. Thank you!

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.

2 Likes

Oh right, so I won’t need to use global variables ever right?

Yeah. Global variables are technically useless.

2 Likes

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.

2 Likes

oh right, so later on we can change the value of the local variable that we have assigned earlier on without any value.

1 Like

It was really helpful and since you were the first to reply I had solutioned it previously : D

Yep. You can also use the multiple variable trick with blank variables, for example:

local Number, Letter
print(Number)
print(Letter)

Number = 1
Letter = "A"
print(Number)
print(Letter)

Again, the first two will print nil and the second two will print 1 and A respectively.

2 Likes

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!!!