So the blog on hunting globals here…
https://coronalabs.com/blog/2016/04/16/check-those-pesky-globals/
I asked a question, basically this…
Can you turn a global local by just declaring it local? Reason I ask,
I set up something like:
local drawOrder = {spriteToDisplay2, spriteToDisplay4, spriteToDisplay1, spriteToDisplay3}it hits that and pounds my console with ‘reading global nils’
Then a little bit later I do:
local spriteToDisplay1=display.newSprite( sheet, sequenceData)
local spriteToDisplay2=display.newSprite( sheet, sequenceData)
etc…and I don’t get any global warnings. I then made a simple test=3 then local test=5, print (test). and got 1 error, where if I don’t put local for test then I get 3 global set warning. So I guess I answered my own question? just want to make sure.
Rob Miracles answer was
Lua is a one pass compiler system. When it is parsing your code and sees spriteToDisplay2 as a variable that has not been previously declared local, it assumes you want a global variable and it gets assigned a memory address.
Later, when you do local spriteToDisplay2… You have created a local version (it has it’s own memory address) and you can use it as a local. However, drawOrder still has the addresses for the global. If your local spriteToDisplay were to go out of scope, it would fall back to the last definition.
It’s best illustrated here:
local number = 10
if true then
local number = 20
end
print (number) — prints 10While I did that with all locals, the concept is the same. Globals are the highest order in scoping. If you use the same name later as a local, it’s a new variable. If you use the same local inside another block and give it a local, its a new variable. As the scope stack pops back up, the version that is in scope at that time becomes active.
Which I think makes sense. As soon as a Corona sees a Var, if it is not defined local, it will allocate it to Global. And if you define it local, it is creating a new address(?) And now there are two. right? So would it be best for me to define the spriteToDisplays as local before the drawOrder references them in its own declaration.
right?
