Auto Localization (Trick) – Lua

Today’s article applies to Lua in general, but should be especially helpful to Corona Users.

The Problem

I tend to use localization a lot in my coding.  In fact, most of my files have (or used to have) long lists of locals at the top where I bring in math, string, and other functions.

local mAbs              = math.abs
local mRand             = math.random
local mDeg              = math.deg
local mRad              = math.rad
local mCos              = math.cos
local mSin              = math.sin
local mAcos             = math.acos
local mAsin             = math.asin
local mSqrt             = math.sqrt
local mCeil             = math.ceil
local mFloor            = math.floor
local mAtan2            = math.atan2
local mPi               = math.pi
local mMin              = math.min
local mMax              = math.max

local getInfo           = system.getInfo
local getTimer          = system.getTimer
local strMatch          = string.match
local strFormat         = string.format
local pairs             = pairs

-- ...

As you can see, these lists are long. This tends to clutter up my files. Also, I tended to have different lists in different files and projects, making maintenance a nightmare.

I have long been looking for a cleaner and faster way to achieve this. Then, one day I say some of Sergey’s code (see setLocals() function) and I was inspired.  I quickly tried his code, but found I didn’t quite understand it and couldn’t make it work.  So, for a while I abandoned the issue.

A Solution

Last week I re-examined this question and asked the community at large for help.

I quickly received some great answers, that lead me to great examples, which in turn lead me to learn more about Lua.  At the end of this effort, I had a better, if imperfect solution.

You can download it here, with example code.

The above code can now be replaced with this:

local mAbs,mRand,mDeg,mRad,mCos,mSin,mAcos,mAsin,mSqrt,mCeil,mFloor,mAtan2,mPi,mMin,mMax,getInfo,getTimer,strMatch,strFormat,pairs;require("autoLoc").run()

 How It Works

If you want to fully grok this trick, you must examine the code in “autoLoc.lua“, however the core of this trick are the ‘debug’ library features:

  • debug.getlocal() – Get value of an indexed local at a certain position in the stack.
  • debug.setlocal() – Set value of an indexed local at a certain position in the stack.

 Using It Yourself

If you choose to use this, do the following:

  1. Add any new localization statements as you need, as you normally would at the top of “autoLoc.lua”.  The module will automatically discover them.
  2. Include “autoLoc.lua” in any files that need these locals.
  3. Declare the locals (using the same names you used in “autoLoc.lua”
  4. After these declarations, call “”.  This will fill in the declared locals.

For clarification, download my samples and take a look.