I have a quick question regarding declaring local variables. I’ve always had this thought that there could be problems caused by declaring a variable multitudes of times, like a memory leak or something.
I don’t know where I came up with the idea, but I’m curious if there are any performance deficits when declaring a variable in Update(), for example.
This is what I do:
local example = 0
local another_example = 0
function Update(self, dt)
example = example + 1
another_example = another_example + example
end
I realize that this calls them local to the entire script, but I’ve always done it this way because of my subconscious thought that doing it this way:
function Update(self, dt)
local example = example + 1
local another_example = another_example + example
end
… was a bad idea.
Again, don’t know where I came up with the idea, but I just wanted to confirm whether my doubts on this were correct. i.e, declaring a variable in Update() has no deficits.
Doing it the first way means the entire script file has access to the variables ‘example’ and ‘another_example’.
Doing it the second way means that the scope of the variables will only be in the update(self,dt) function, which is generally the behavior you want. Always try to minimize the scope of your variables.
For more info, this (scope in the manuals) is a good place to look, but these principles of scope are general in Lua, and not just Defold. Their scope is global, if you will! 
1 Like
Right, I understand the scopes they’re given when declaring them, but there’s no issue with declaring the same variable multitudes of times?
No. Variables in Lua are all set to ‘nil’ by default, so unlike languages like Java, there is no difference between the declaration of a variable and giving it a value.
2 Likes
One implication of declaring local variables outside the scope of the lifecycle functions is that they will be shared by all instances of the script. It can be useful if you need to share data between script instances but it could also be a source of bugs.
2 Likes
Just for having the same words for it: In C++ declaring is where you put the “int var;”, defining is where you assign it a value (“var = 0;”)
Although there probably isn’t much overhead from having the variables assigned to twice, I think having two places where it is initialized is a source for both trouble and confusion.
2 Likes