sample code is full of constructs like: local physics = require(“physics”), and similarly for other libraries. But unlike other libraries, physics pollutes the global namespace with itself anyway, consider the following:
local phyzikz = require(“physics”)
print("phyzikz = " … tostring(phyzikz)) – here’s my local
print("physics = " … tostring(physics)) – huh? a global too? that’s weird
print("_G.physics = " … tostring(_G.physics)) – yep, there it is
then contrast that with widget or storyboard, for example:
local wijit = require(“widget”)
print("wijit = " … tostring(wijit)) – here’s the local as expected
print("widget = " … tostring(widget)) – and nil, as expected, nice and clean
local stoaribored = require(“storyboard”)
print("stoaribored = " … tostring(stoaribored)) – here’s the local as expected
print("storyboard = " … tostring(storyboard)) – and nil, as expected, nice and clean
It causes all sorts of weirdness. For example let’s say you use the example code exactly as written, expecting it to work exactly as described. You *should* then be able to release the library by nil’ing out the “physics” reference, right? Just as with any other local. But it’s more confusing than that:
local physics = require(“physics”)
–
– let’s confirm that unintended global:
–
print("_G.physics = " … tostring(_G.physics)) – yep
–
– now lets try to wipe out our local as if we weren’t aware of this problem
– scoping rules mean plain old “physics” is our local, no confusion yet
–
physics = nil
–
– so let’s check our local
–
print("physics = " … tostring(physics))
–
– huh? still there?? i expected “nil”!! WTF!!!
– just kidding, for dramatic effect, of course we DID wipe the local
– but to a “novice”, or even an experience developer who was simply naive to this problem,
– it doesn’t APPEAR we wiped it, because that print statement just resolved to a variable of
– the same name in global scope that you didn’t even know existed, doh!
–
print("_G.physics = " … tostring(physics)) – aha, global is still there, masquerading as our supposed local
–
– so let’s release the global too
–
_G.physics = nil
print("physics = " … tostring(physics))
–
– finally, success!! sheesh, that thing was hard to get rid of!
–
So why do *I* care? Because I lock _G after setting up the very few globals that I need. I have it wrapped in a handler that screams and yells and calls me dirty names whenever it notices I tried to alter the global environment - which happens any time I enter a scene with “local physics = require(“physics”)”.
I try to tell the handler “hey, it’s not my fault, it’s Corona!” but it doesn’t pay any attention to me.