In my addon, I had the following line of code
GetBagName = _G.GetBagName
Which raises the dreaded Your AddOn has been blocked error.
My intention was that the global GetBagName API method would be cc’d into my AddOns ‘namespace’, i.e., global to my other AddOn’s files. However, looking at other AddOns they initialize _G methods as local. For example
FILE: foo.lua
local GetBagName = _G.GetBagName
So, when I made GetBagName local, the Blocked AddOn message went away.
So far, so good but… obviously, I do not fully understand the semantics of the _G table. Doesn’t initializing GetBagName as a local variable restrict the visibility of that method to the particular file within which it resides? If not, why not? Second, but unrelated question: Why copy methods from the _G table in the first place? Performance?
Thanks
GetBagName being global, putting the _G. in front of it is redundant as _G is a reference to the global table (ie, you’re saying GetBagName = itself).
local GetBagName = _G.GetBagName is creating a pointer to the global function entry thus avoiding the table lookup making it slightly more efficient.
That said, local GetBagName = _G.GetBagName
and then only calling GetBagName in your code once is also reduntant as you wasted the “efficiency” assigning the global to the local ie. only localise globals that will be called often like in loops etc…
local is local to the chunk it is in, not just the module (file) as a whole.
local someVar = 2
if something then
local someVar = 3
print(someVar) -- 3
end
print(someVar) -- 2
I get it. Thanks. My addon makes extensive use of Blizz’s container functions. Per your advice, I’ve gone back through the code and localized only these globals that are frequently called.
Cheers
P.S. Oh, and the dreaded Your AddOn has been blocked error was directly related to this issue. I had declared these functions as follows:
GetBagName = _G.GetBagName
When I changed it to…
local GetBagName = _GetBagName
Everything worked fine.
Something that should also be mentioned is that the global space (table) is shared by all addons including Blizzard UI code. Every function, variable, table etc. you create without “local” (or being an element of a non-global table) is placed in that global space.
By convention (divine right) and the fact that for the most part Blizzard code is loaded before any other addons, they get to use “common” names for globals and you should try an make yours unique by some means like addon name/acronym prefix or some such.