ProTip for Corona: Finding Typos

One of the most common mistakes in programming is typos.   Your brain wants to type one thing and your fingers another.

In Corona (and Lua in general), variables aren’t declared explicitly before you use them.  When  Lua sees a variable name that you haven’t declared as local, it starts looking up the chain of scopes until it reaches the Global namespace (_G).  If it gets there, it creates a key in the _G table with your variable name.

This little trick (shown to me by my friend Chris Blackwell) makes Corona tell you whenever this happens.  Sometimes it’s fine, but most of the time you’ll find a typo (as I did in the Particle Candy library).   I even found that loading the built-in JSON library causes it to check for a global called “Chipmunk.”  Granted, Chipmunk isn’t a typo, but it is accessing a variable that doesn’t exist.  This can happen if you’re check to see if something has been loaded or not.  In those cases this warning can be ignored.

So, put this in your app’s main.lua, run your app in the simulator and watch the console output.  You might just find a problem you didn’t know you had.

Note: You only want this in debug builds.  You could wrap it with a check for running on the simulator, but the best bet is to just remove it before building your final version.

local globalsmeta = {
__index = function(table, key)
print("!!! access to nonexistent global variable "..tostring(key).."n"..debug.traceback())
setmetatable(_G, globalsmeta)

This works by adding a metatable to the Global namespace to call this function whenever you access an unknown key in its table.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.