WoW:Getting started with writing AddOns: Difference between revisions

no edit summary
No edit summary
Line 97: Line 97:
Beware Lua functions and variables are globals by default and are directly visible to the other addons. If authors blindly use simple and common names, like:
Beware Lua functions and variables are globals by default and are directly visible to the other addons. If authors blindly use simple and common names, like:
<pre>
<pre>
addonEnabled = true;
addonEnabled = true;
function GetArrowsCount()
function GetArrowsCount()
   ...
   ...
end
end
</pre>
</pre>


An addon will easily conflict with variables of the same name from other addons or from the Blizzard interface. Instead, you should write your addon more like a Lua module: place all the data and functions in a single global table, named after the addon, and use local declarations otherwise (no other globals), like:
An addon will easily conflict with variables of the same name from other addons or from the Blizzard interface. Instead, you should write your addon more like a Lua module: place all the data and functions in a single global table, named after the addon, and use local declarations otherwise (no other globals), like:
<pre>
<pre>
MarksmanAddOn = { };              -- about the only global name in the addon
MarksmanAddOn = { };              -- about the only global name in the addon
local addonEnabled = true;        -- local names are all ok
local addonEnabled = true;        -- local names are all ok
function MarksmanAddOn:GetArrowsCount()
function MarksmanAddOn:GetArrowsCount()
  ...                            -- function is now inside the global table
  v...                            -- function is now inside the global table
end
end
MarksmanAddOn.arrowsCount = MarksmanAddOn:GetArrowsCount()
MarksmanAddOn.arrowsCount = MarksmanAddOn:GetArrowsCount()
</pre>
</pre>


For large add-ons this can get complicated, and the current version of Lua doesn't offer much to help. Use a full, clear, name for the global table, and assign a shorter name in your .lua files, like:
For large add-ons this can get complicated, and the current version of Lua doesn't offer much to help. Use a full, clear, name for the global table, and assign a shorter name in your .lua files, like:
<pre>
<pre>
local mod = MarksmanAddOn;
local mod = MarksmanAddOn;
   
   
-- then you can write
-- then you can write
mod.arrowsCount = mod:GetArrowsCount()
mod.arrowsCount = mod:GetArrowsCount()
</pre>
</pre>