This is used to keep your variables not pollute the _G, and gain some code flexibility.Also, the up-value is not as quick as you think.
Here is a test, a() function contains a long calculation, and after it, there are three call types :
1. Define function in the global, call the global function directly.
2. Define up-values, the use the up-values to "speed up" the calculation.
3. Use the standalone environment, do the calculation.
Lua Code:
do
function a()
local sum = 0
for i = 1, 100000 do
sum = sum + i
end
end
oclock = os.clock
do
-- Normal calls
function callA()
collectgarbage()
local startTime = oclock()
for i = 1, 10000 do
a()
end
local finsih = oclock()
print("Normal cost ", finsih - startTime)
end
callA()
end
do
-- so la, loclock are up-value
local la = a
local loclock = oclock
function callA()
collectgarbage()
local startTime = loclock()
for i = 1, 10000 do
la()
end
local finsih = loclock()
print("Up-value cost ", finsih - startTime)
end
callA()
end
do
local addon = {}
if not getmetatable(addon) then
setmetatable(addon, {
__index = function(self, key)
-- keep vars in the _G to the addon to reduce the access cost
local v = _G[key]
if v ~= nil then
rawset(self, key, v)
return rawget(self, key)
end
end,
__metatable = true,
})
end
setfenv(1, addon)
-- Make sure metatable operations won't happen again when call callA
a = a
oclock = oclock
-- so a, oclock are global in the environment, not up-value
function callA()
collectgarbage()
local startTime = oclock()
for i = 1, 10000 do
a()
end
local finsih = oclock()
print("Standalone environment cost ", finsih - startTime)
end
callA()
end
end
The result may not be exactly because there are too many things should cost the cpu in the same time, but you can see a lot in it, I run these code three times in lua 5.1.2 on mac shell:
Normal cost 16.129601
Up-value cost 16.357202
Standalone environment cost 16.308925
|
Normal cost 16.197299
Up-value cost 16.478886
Standalone environment cost 16.390823
|
Normal cost 16.203371
Up-value cost 16.468056
Standalone environment cost 16.404645
|
So the up-value part is the slowest.
In an addon, you don't need access all things in the _G, only what you need is saved to your addon, and if you want access something once, you always can do it like :
print(_G.CAT_FORM)
Just access if from _G table, you won't save the CAT_FORM in your addon.