Corona Quick Thought – strict.lua or GLOBAL_lock()

Given that Lua is such a dynamically language, it is trivially easy to accidentally “litter” the global environment with variables you didn’t intend to be global. Even a simple “spelling error” (or a camelCase accident one way or the other) can introduce a new variable, and fail to set the intended variable – a “silent” error that Lua won’t complain about but may have unintended and hard-to-diagnose consequences in your code. For example:

Of course, this problem isn’t unique to Corona. For instance, it’s well-described here along with several approaches to address it, including strict.lua and Niklas Frykholm’s GLOBAL_lock/unlock().

I’ve used both in the past, and both are directly usable in Corona, no special mucking about required. Effectively, what either of them do is lock the global environment, preventing unintended access afterward, and generating an error if you attempt to do so.

If using GLOBAL_lock/unlock you can just copy the code from the wiki. If you wish to use strict.lua, I’d suggest getting it directly from the 5.1.5 source tarball available here (it’s in the etc directory). (as of this writing, Corona is still using JNLua 0.9, so 5.1.5 would be the right match)

To use either, you may need to hunt for a “safe spot” in your code after you’ve declared any intended globals, for example:

Next, you’ll want to give your app a thorough testing, exercising all of its code, as such errors can’t be noticed until execution. Then go about cleaning them all up.

Note that you may have to specifically “exempt” certain Corona modules which themselves leak globals, particularly if using GLOBAL_lock/unlock (which, oddly, is a bit “stricter” than “strict” 😀 ), for example:

Also note that you probably would not want to keep either active in a production build — better to accidentally assign a global somewhere than crash hard with a debug-environment error, just in case your testing didn’t uncover absolutely everything. One way you can do this (there are several of course) might be to wrap all of that code inside some kind of conditional, for example you might test if running on the simulator, and if so stub out all those routines to do nothing instead, so you can leave the rest of your code as-is, for example:

Leave a Reply