View Single Post
08-25-13, 06:00 AM   #15
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
Originally Posted by Malsomnus View Post
This is why I can't quite figure out the general statement "define variables in the lowest scope possible"
Here's an example:

Code:
local unit
for i = 1, 4 do
    unit = "party"..i
    print(UnitName(unit), "is a", UnitClass(unit))
end
In this example, the "unit" variable is only used inside the "for" loop, and its value is dependent on the iterator's value, so it should only be defined in that scope, not in a higher scope:

Code:
for i = 1, 4 do
    local unit = "party"..i
    print(UnitName(unit), "is a", UnitClass(unit))
end
On a side note, in some cases, the narrowest scope necessary for a variable is no scope at all. I've definitely seen cases of this in addons:

Code:
local x = 4
for i = 1, x do
    local unit = "party"..i
    print(UnitName(unit), "is a", UnitClass(unit))
end
In that case, the variable "x" doesn't need to exist at all; you should just use its value directly in the loop construction, as in the previous example.
__________________
Retired author of too many addons.
Message me if you're interested in taking over one of my addons.
Don’t message me about addon bugs or programming questions.

Last edited by Phanx : 08-25-13 at 06:04 AM.
  Reply With Quote