I've seen many addons using global variables very frequently in LUA. It's easy to forget the local and tedious to put it in front of every variable, however globals can pollute the environment to an extend where several addons unintentionally interact with each other. Just imagine you have a global called i that stores your current list index, and another addon does just the same and puts any arbitrary value in i, that would cause either addon or both to crash.

There are several solutions to this issue:
  • Trion could implement separated environments for each addon. But this would mean that addons could no longer communicate except through dedicated APIs (which isn't that bad just more complex).
  • The author of an addon uses namespaces to make sure nothing is leaked.

Namespaces allow you - the author - to put all your code including all your global variables in a table. Since the "global" namespace is nothing but a table either, this can be done very easily with LUA: you just have to point the environment from "global" to your private addon table through the function setfenv. The function below does exactly that:

function namespace(name)
  local t = setmetatable({}, {__index = _G})
  _G[name] = t
  setfenv(2, t)
Using that function at the top of your file like this:
You ensure that all variables and functions are declared in your addon's namespace. So a variable i becomes myAddon.i making sure that no addons can accidentally overwrite each other's global variables. And the best about it, is that you don't even have to change a single line of code, as LUA will automatically look up all variables in the right place, which is first your addon's namespace and then the global environment.

The only catch is that you now have to explicitly denote that you want to change the global namespace if you really want to have a global variable. This is required for example to access and modify the saved variables. This can be done by explicitly stating the global namespace like this:
function onVariablesSaveBegin()
  _G.MyAddon_SavedVariables_Character = Settings_Character
You can use the same names for these variables, but then it might get a little confusing, therefore it is recommended to use different names for the global and for the local variable holding the SavedVariables content.