Thread: Addon Etiquette
View Single Post
04/21/14, 11:57 AM   #23
Seerah
Fishing Trainer
 
Seerah's Avatar
WoWInterface Super Mod
AddOn Author - Click to view addons
Join Date: Feb 2014
Posts: 648
There is no such thing as a "local global" variable.

Variables are in the global scope by default, unless they are declared as local by placing the word local before the declaration of the variable.
Lua Code:
  1. local myVariable = 5     --this is in the local scope
Local variables are available to the scope they are created in and anything below that scope.
Lua Code:
  1. local myVariable = 5
  2. local function WhatIsMyVariable(var)
  3.      local varToPrint = var
  4.      print(varToPrint)
  5. end
  6.  
  7. WhatIsMyVariable(myVariable)     --prints out 5 because myVariable and the local function were both defined in this scope (the main chunk of the Lua code)
  8. WhatIsMyVariable(varToPrint)     --gives a nil error because varToPrint was defined at a lower scope (inside the function) it's not available at a higher scope (outside the function)

Variables should be declared local if and whenever possible. This is both to reduce the chance for collision with other leaked global variables with the same name by other authors, and for a boost in performance.

A variable should only be made global if access from outside of the file it is declared in is necessary. (Ie, referencing the function in an XML file, in-game debugging, support for other addons to have access...)

If a variable is in the global scope, it should have as unique a name as possible. This unique name should contain reference to your addon, since it's likely the user only has one addon with that name installed.
Lua Code:
  1. SavedVariables = {}     --bad - generically named global variable
  2. MyCoolAddon_SavedVariables = {}     --good - uniquely named global variable

What most people miss is that frame names are GLOBAL REFERENCES to that frame. These need to be uniquely named objects as well.
Lua Code:
  1. local frame = CreateFrame("MyFrame", GuiRoot, CT_CONTROL)
  2. --the local variable and the global reference both point to the same frame in memory
  3. d(frame)     --prints out userdata:459efj9
  4. d(MyFrame)     --prints out userdata:459efj9
If some other author also cleverly decides to give their control a global name of MyFrame, whichever one is created second will overwrite the first and the two addons will break each other. (The same is true for any other global variable.)
  Reply With Quote