View Single Post
08-16-05, 09:44 AM   #8
Littlejohn
A Warpwood Thunder Caller
AddOn Author - Click to view addons
Join Date: Jun 2005
Posts: 90
The cascaded "if" is really common in WoW code. Most event handlers have a huge chain of "if ... else if ... else if ...". Lua runs these surprisingly fast, but your idea of using a table to avoid the "if" statement is really good. This kind of code is much easier to maintain and improve -- it's more object oriented. Here's what you wrote:
Code:
class = <playerclass>

Global_options = {'a','b','c'};
Warrior_options = {'d','e','f'};
Rogue_options = {'g','h','i'};

append class .. '_options' to Global_options;
That's pretty close to how it would be in Lua:
Code:
local _, class = UnitClass('player')

Global_options = {'a','b','c'}
WARRIOR_options = {'d','e','f'}
ROGUE_options = {'g','h','i'}

for k,v in getglobal(class .. '_options') do
    table.insert(Global_options, v)
end
I'm using the second class name from UnitClass() because it should work in any language version of WoW. (You won't have to worry about translating this if a German player for example wants to use your mod.)

There's no real reason to use global variables for each class though -- and there are good reasons not to: (1) you have to use a special function getglobal() to fetch them, and (2) you've got more global variables to worry about module conflicts. I think this is a little bit cleaner:
Code:
local _, class = UnitClass('player')

Global_options = {'a','b','c'}
Class_options = {
    WARRIOR = {'d','e','f'},
    ROGUE = {'g','h','i'}
}

for k,v in Class_options[class] do
    table.insert(Global_options, v)
end
Don't forget that if you use tables instead of pseudo-arrays that you'll have to change the append logic:
Code:
local _, class = UnitClass('player')

Global_options = {a = 1, b = 2, c = 3}
Class_options = {
    WARRIOR = {d = 'foo', e = 5, f = 6},
    ROGUE = {g = 'bar', h = 10, i = 100}
}

for k,v in Class_options[class] do
    Global_options[k] = v
end
  Reply With Quote