12.07.2015 Views

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

Wiley-World.of.Warcraft.Programming.A.Guide.and.Reference.for.Creating.WoW.Addons

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Appendix A ■ Best Practices 1321Use Tables as a Logic StructureSometimes you will have a long chain <strong>of</strong> if ... elseif where each clausecompares the same variable to some constant. The prime example in addonprogramming is an OnEvent script. Consider the following:if event == “SOME_EVENT“ then-- do stuffelseif event == “ANOTHER_EVENT“ then-- do stuffelseif event == “THIRD_EVENT“ then-- do stuffelseif event == “FOURTH_EVENT“ then-- do stuffendYou can use a table in a manner similar to the ‘‘Rework Repetitive Code’’section earlier in this appendix. Instead <strong>of</strong> the if statement, you fill a tablewith functions indexed by the name <strong>of</strong> the event:local eventH<strong>and</strong>lers = {[“SOME_EVENT“] = function(frame, namedArgument)-- do stuffend,[“ANOTHER_EVENT“] = function(frame, namedArgument1, namedArgument2)-- do stuffend,[“THIRD_EVENT“] = function(frame)-- do stuffend,[“FOURTH_EVENT“] = function()-- do stuffend}Now the OnEvent script can be simplified to four lines (or one if you arecareful about what events you register):function MyEventH<strong>and</strong>ler(frame, event, ...)local h<strong>and</strong>ler = eventH<strong>and</strong>lers[event]if h<strong>and</strong>ler thenh<strong>and</strong>ler(frame, ...)endendThis technique af<strong>for</strong>ds a few advantages:The underlying architecture <strong>of</strong> the table lookup usually executes morequickly than a string <strong>of</strong> if ... elseif clauses, especially with a largenumber <strong>of</strong> entries.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!