OK. I still want something, better, but this works for those who want to use it. Do the following.
Add this code into a module named “autolocalize.lua”
local function go( module ) local mod = require( module ) local i = 1 while(debug.getlocal(2,i) ~= nil ) do local name,value = debug.getlocal(2,i) --print(name,value) if(mod[name] ~= nil) then --print(“Found”, name, mod[name] ) debug.setlocal(2,i,mod[name]) end i = i + 1 end end local public = {} public.go = go return public
Use it like this:
local min,max,sqrt,random; require(“autolocalize”).go(“math”) local getTimer,getInfo; require(“autolocalize”).go(“system”)
I tried your idea out too and unfortunately, that was slower. I was stymied for a moment, then I realized, we’re paying a penalty for the temporary string.
Either way, you create a temporary string, which costs time:
I like your solution better, because it lets me use custom spellings for my locals!
Here is the module:
local mMin,mMax,mSqrt = math.min,math.max,math.sqrt local function go() local locals = {mMin=mMin,mMax=mMax,mSqrt=mSqrt} local i = 1 repeat local k, v = debug.getlocal(2, i) if k then if v == nil then if not locals[k] then print('No value for a local variable: ' .. k) else debug.setlocal(2, i, locals[k]) end end i = i + 1 end until nil == k end local public = {} public.go = go return public
Here is the usage:
local mMin,mMax,mSqrt; require("autolocalize2").go("math")
This works on the simulator and on my device.
Notice, I made a slight change to your code. See the first line of the module. Create custom locals in the module, then set them later in the calling file.
Good to know you wound up with something you like.
Looking over the mailing list link, the first case seems to be using Lua 5.2 (it mentions _ENV, for instance), so I’d guess it was just an incompatibility on account of the environment-related changes in the newer version.
On that other comment, accessing math.random… the string will have been interned at that point (actually, earlier, when the math library is loaded), so it ends up being a constant (just its hash, actually). However, the VM will still have to do lookup in mMath, versus using slightly cheaper bytecode that just reads out of a local slot directly.