The most important practice when declaring variables is to minimize the scope of the variable as much as possible.
For example, if you create a for loop that requires a variable to be used only in that loop, you’d declare it inside the loop’s scope to prevent yourself from accidentally referencing it later on in the code.
Declare variables with the local keyword when you don’t require it to be used outside of its scope.
Here’s a small example of my explanation.
function SomeFunction()
for (i = 1, 10) do
local multiplied = i * 100
end
end
The multiplied variable was declared locally, and within the for loop’s scope. I can be sure not to make the mistake of accidentally referencing it later on in the code. It also allows me to re-use the same variable name for another loop if needed.
function SomeFunction()
local multiplied = 1
for (i = 1, 10) do
multiplied = i * 100
end
end
The multiplied variable was declared locally within the SomeFunction scope. Meaning it can only be used within SomeFunction.
function SomeFunction()
for (i = 1, 10) do
multiplied = i * 100
end
end
The multiplied variable was declared globally, meaning every line and method after its declaration will have access to this variable.
As for your question regarding memory. You can try to decrease the amount of variables holding references that will only be used once by just not declaring the variable. It frees up some names and memory. Variables are very useful if you constantly need a reference to a certain object without having to find it yourself if it ever moves around too much or is constantly used.
I wouldn’t worry too much about memory since you’re not designing some triple A game or memory intensive program.
Don’t think so, I mean, one it makes the code look more professional and two it’s easier to read. I don’t think there’s a performance difference between these 2 codes.