Question about global variables vs self

Hi, I have a little question about global variables vs the variables inside “self”. What are the differences, benefits and best practices between them ?
Like: local player_position vs self.player_position
Thanks.

You can check the docs on that subject: http://www.defold.com/manuals/lua/#_locals_globals_and_lexical_scoping

Basically, global variables (a = 10) are available everywhere, local variables (local a = 10) are available to all instances of that script file, and self properties (self.a = 10) are only available to that specific script instance.

2 Likes

Thanks, I already knew that.
But which one should I use, Global or Self. I really care about how much the memory they are using.

Example:

local point = 100

function init(self)
self.point = 100
end

function A(self)
--using point here
--or using self.point here
--which one is better
end

Ah, I see. Well if a before-and-after check of profiler.get_memory_usage() means something, then it uses exactly the same amount of memory either way.

1 Like

If you have no specific reason for using a global, store your data in self. It will most likely save you from future problems.

2 Likes

All of you guys, I really thank you.

1 Like