Documente Academic
Documente Profesional
Documente Cultură
Ace3GettingStartedWoWAddOnsWowAce
Addons Authors Forums Wiki Store Paste
Signin Registernewaccount
Search...
Ace3
Overview
Files
Images
Tickets
Pages
Repository
Localization
Subscriptions
Donate
GettingStarted
KeepinmindwhenreadingthroughthisthatAce3isdesignedtobemodular:notalladdonsmayneedtouseeveryportionofit.
Feelfreetopickandchoosethosewhichsuitthepurposesofyouraddon,andskipoversectionsrelatingtobitsyoudon'tneed.
BasicAddonFileSetup
Startbycreatingafolderfortheaddonin<WoWDirectory>\Interface\Addons.Thenamecanbewhateveryouwantaslongasit's
unique,sopicksomethingdescriptiveofwhatyou'rewriting.Withinthatdirectory,you'llthenwanttocreatesometextfiles:
.tocfile
Thisfileshouldbenamedthesameasthefolder,exceptwith".toc"addedtotheend.It'sabasictextfilethattellsWoWwhatother
filestheaddonneedstoload:
##
##
##
##
##
Interface: 40000
Title: My Addon's Title
Notes: Some notes about this addon.
Author: Your Name Here
Version: 0.1
embeds.xml
Core.lua
Thelineswhichbeginwith##provideinformationaboutyouraddonitselftoWoW-forinstance,"Interface"specifiestheinterface
versionyouraddonwasdesignedtobeloadedwith(atthetimeofthiswriting40000),"Title"specifieshowthenameoftheaddon
shouldbedisplayedintheaddonwindow,etcetera.
Afterthe##lines,therestofthe.tocfileissimplyalistoffilesthatmakeuptheaddon.Usingaseparatefilenamed"embeds.xml"
isafairlycommonlyacceptedwaytospecifywhichlibrariesyouwanttoembedinyouraddon(suchasAce3libraries).Also,most
addonswilltypicallyhaveatleastone"main"Luafilewhichhastheinitialcodetosetuptheaddon-somepeopleliketobe
consistentandcallthissomethinglike"Main.lua"or"Core.lua"ineveryaddon,othersprefertonamethemaincodefileafterthe
addonitself,likethe.tocfileexceptwitha.luaextension.
embeds.xml
Usethisxmlfiletospecifythelocationsoflibrariesthatshouldbeloaded(typicallyreferencingthelibrary'sownXMLfilevia
Include).Asanexample,usingLibStubandloadingapairofAce3librariesfromaLibssubdirectoryintheaddon'sfolder:
<Ui xsi:schemaLocation="http://www.blizzard.com/wow/ui/ ..\FrameXML\UI.xsd">
<Script file="Libs\LibStub\LibStub.lua"/>
<Include file="Libs\AceAddon-3.0\AceAddon-3.0.xml"/>
<Include file="Libs\AceConsole-3.0\AceConsole-3.0.xml"/>
</Ui>
AdditionallibrariescanbeaddedbyaddingadditionalIncludelines.Youcouldalsoreferenceeachlibrary'sxmlfileinyouraddon's
.tocfileinstead,butembeds.xmlhelpsmakeitclearerwhichpartsofthecodebelongtotheaddonitself,andwhicharepartof
sharedlibraries.
Core.lua
History
Tableofcontents
1.BasicAddonFileSetup
1.1..tocfile
1.2.embeds.xml
1.3.Core.lua
2.UsingAceAddon-3.0
2.1.Creatinganaddonobject
2.2.Standardmethods
3.UsingAceConsole-3.0
3.1.IncludingAceConsolefunctionality
3.2.UsingAceConsoleforoutput
3.3.UsingAceConsoleforslashcommands
4.UsingAceConfig-3.0
4.1.Creatinganoptionstableandhandlers
4.2.Registeringtheoptions
5.UsingAceDB-3.0
5.1.PreparingSavedVariables
5.2.InitializingAceDB
5.3.Persistingdatavalues
5.4.Workingwithprofiles
6.UsingAceDBOptions-3.0
7.UsingAceEvent-3.0
7.1.IncludingAceEventfunctionality
7.2.Subscribingtoevents
7.3.Sending/receivinginter-addonmessages
8.UsingAceComm-3.0
8.1.IncludingAceCommfunctionality
8.2.Sendingmessagestootherclients
8.3.Receivingmessagesfromotherclients
9.UsingAceHook-3.0
9.1.IncludingAceHookfunctionality
9.2.Hookingfunctions
9.2.1.Standardhooking
9.2.2.Rawhooking
9.2.3.Securehooking
9.3.Hookingscripts
9.4.Checkingtoseeifsomethingisalreadyhooked
10.UsingAceLocale-3.0
10.1.Registeringtranslations
10.2.Usingtranslations
10.3.Mixed-invariables
11.UsingAceSerializer-3.0
11.1.IncludingAceSerializerfunctionality
11.2.Serializingdataforoutput
11.3.Loadingdatafromaserializedstring
Thisfiledoesn'thavetobenamed"Core.lua"-itcanbeprettymuchanythingwitha.luaextension,aslongasyoureferenceitin
your.tocfile.Your.luafileswillcontaintheactualcodewhichrunsyouraddon.Forthebasicsofwhatshouldbeinheretomakea
completelyAce3-basedaddon,seethesectionbelowentitled"UsingAceAddon-3.0".
Facts
UsingAceAddon-3.0
Datecreated
Oct02,2008
Creatinganaddonobject
Lastupdated
Oct27,2010
Aftermakingsureyou'veproperlyreferencedtheAceAddon-3.0library,aswellasLibStub(seetheabovesections),themainLua
filefortheaddon(suchasCore.lua)cancreateanAce3addoninstancelikeso:
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
ThisprovidesyouwithanaddonobjectthatcanbereferencedforallofAceAddon'scallsrelatedtoyouraddon.Inaddition,ifyou
wishtoprovidecertainextrafunctionalitytiedintoyouraddon'sobject,youcanuse"mixins"thatmergeinotherlibraryfunctionsforinstance,usingthefollowinginsteadwouldgiveyouthechatinteractionabilitiesprovidedbyAceConsoleinadditiontothe
AceAddonmethods:
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceConsole-3.0")
Source
Authors
Nevcairiel
mikk
Aiiane
Standardmethods
AceAddontypicallyexpectsyouraddontodefine(typicallyinyourmainLuafile)3methodsthatitcallsatvariouspoints:
function MyAddon:OnInitialize()
-- Code that you want to run when the addon is first loaded goes here.
end
TheOnInitialize()methodofyouraddonobjectiscalledbyAceAddonwhentheaddonisfirstloadedbythegameclient.It'sagood
timetodothingslikerestoresavedsettings(seetheinfoonAceConfigformorenotesaboutthat).
http://www.wowace.com/addons/ace3/pages/gettingstarted/
1/8
3/7/2016
Ace3GettingStartedWoWAddOnsWowAce
function MyAddon:OnEnable()
-- Called when the addon is enabled
end
function MyAddon:OnDisable()
-- Called when the addon is disabled
end
TheOnEnable()andOnDisable()methodsofyouraddonobjectarecalledbyAceAddonwhenyouraddonisenabled/disabledby
theuser.UnlikeOnInitialize(),thismayoccurmultipletimeswithouttheentireUIbeingreloaded.
UsingAceConsole-3.0
IncludingAceConsolefunctionality
AsmentionedaboveintheAceAddonsection,theeasiestwaytoaccessAceConsolefunctionalityinafullyAce3-basedaddonisto
simplyincludeitasalibrarymixinwhencreatingyouraddonobject:
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceConsole-3.0")
Mostexamplesinthissectionwillassumeyou'veusedAceConsoleasamixin.However,ifyouwishtoaccessthelibraryasa
separateobject,youcanloaditviaLibStub:
MyConsole = LibStub("AceConsole-3.0")
UsingAceConsoleforoutput
OutputwithAceConsoleissimple-justcallits:Printmethodwiththetextyouwanttooutput.Ifusedasamixin,AceConsolewill
giveyouraddonobjectthe:Printmethod,otherwise,usethe:Printmethodoftheconsoleobjectyou'vecreated:
-- AceConsole used as a mixin for AceAddon
MyAddon:Print("Hello, world!")
-- AceConsole used separately
MyConsole:Print("Hello, world!")
Bydefault,:Print'dtextwillgotothedefaultchatframe.Ifyouwishtoprinttoadifferentframe,simplypassthatasthefirstargument
to:Print,likeso:
MyAddon:Print(ChatFrame1, "Hello, World!")
UsingAceConsoleforslashcommands
Toallowyouraddontoprocessslashcommands,youneedtoregisterthem,andprovideareferencetoafunctionthatwilldothe
processing.ThisisdoneviaAceConsole'sRegisterChatCommand()method.Notethatthefirstargument(thecommand)shouldnot
includeaslash.Thesecondargumentcanbeeitheramethodnameofyouraddonobjectoranactualfunction.
MyAddon:RegisterChatCommand("myslash", "MySlashProcessorFunc")
function MyAddon:MySlashProcessorFunc(input)
-- Process the slash command ('input' contains whatever follows the slash command)
end
However,inmanycasesitmaybesimplertonotcodetheprocessingofslashcommandsbyhand,andinsteadutilizeAceConfig's
abilitytogenerateslashcommandsautomatically.ReadonforhowtouseAceConfigtosetupaddonoptions.
UsingAceConfig-3.0
Creatinganoptionstableandhandlers
AceConfigisdesignedtomakeiteasyforyoutoprovideaccesstoyouraddon'soptions,whilealsokeepingconfiginterfaces
somewhatconsistentfortheenduser.Inordertodothis,AceConfigautomaticallygeneratestheactualinterfaceusedtomodify
settings:asanaddonauthor,yousimplyneedtoprovideitwiththeinformationaboutwhatoptionsyouwanttomakeavailableand
howtohandleworkingwiththem.ThisisdonebydefiningatablewhichispassedtoAceConfig.Abasicexampleisshownbelow:
local options = {
name = "MyAddon",
handler = MyAddon,
type = 'group',
args = {
msg = {
type = 'input',
name = 'My Message',
desc = 'The message for my addon',
set = 'SetMyMessage',
get = 'GetMyMessage',
},
},
}
Theaboveoptionstabledefinesasinglesetting,"msg",whichisatextualinput(type='input')setting.setandgetcanbeeither
methodnamesofyouraddonobject(orwhateverobjectisdefinedashandler),orfullfunctions.Thosemethodsorfunctionswillbe
calledwheneverthecorrespondingactionisrequestedforthatsetting.Sotheymightbesetupsomethinglikethis:
function MyAddon:GetMyMessage(info)
return myMessageVar
end
function MyAddon:SetMyMessage(info, input)
myMessageVar = input
end
Formoredetailsonthevarioustypesofsettingsavailableandtheirpossiblemodifierflags,seetheAceConfig-3.0documentation.
http://www.wowace.com/addons/ace3/pages/gettingstarted/
2/8
3/7/2016
Ace3GettingStartedWoWAddOnsWowAce
Registeringtheoptions
Oncetheoptionstableisdefined,itneedstoberegisteredwithAceConfig.Thiswillalsoautomaticallytieittoslashcommand(s)if
youchoose.Toregisterit,useLibStubtoobtainanAceConfig-3.0object,andcallitsRegisterOptionsTable()method:
LibStub("AceConfig-3.0"):RegisterOptionsTable("MyAddonName", options, {"myslash"
Thethirdargumentisalistofslashcommandsyouwanttiedtothisoptionset.Ifyoudon'twishtotieanyslashcommandtoyour
options(i.e.ifyouonlywantGUIconfigurationorsomesuch),setthethirdargumenttonil.
UsingAceDB-3.0
PreparingSavedVariables
Inordertopersistanythingfromoneloadofanaddontothenext,theaddonmustspecify(viatheSavedVariablesTOCfield)what
tosave.Acommonconventionistouseatablenamedthesameastheaddonwitha"DB"suffixtostorethedatawhichshouldbe
persisted:
## SavedVariables: MyAddonDB
Theaboveshouldbeaddedtotherestofthe##linespresentintheaddon's.tocfile.Thisisnecessarytopersistanysettingseven
ifnotusingAce;AceDBsimplyprovidesamoreeasilyaccessiblelayerontopofSavedVariables.
InitializingAceDB
ItisimportanttounderstandthatAceDBislayeredontopofSavedVariables,andthusinorderforAceDBtobeabletoload
previouslysavedvalues,itneedstobeinitializedaftertheSavedVariablesvalueshavebeenloaded.Whatthismeansforaddon
authorsisthatyoushouldn'tcreateyourinstanceofAceDBinthemainchunkofyouraddon,butinsteadwaittodoituntil
OnInitialize()orlater:
function MyAddon:OnInitialize()
self.db = LibStub("AceDB-3.0"):New("MyAddonDB")
end
ThefirstargumentpassedtoNew()shouldbethenameoftheSavedVariablesyousetupintheTOC.Youcanalsopassatable
specifyingdefaultvaluesfortheDB(ifitdoesn'talreadyexist)andadefaultprofile,ifyouwish.Also,abriefnoteformoreadvanced
authors:ifforsomereasonyouraddoncausesLoadAddon()tobecalledinthemainchunk,OnInitializewillfireprematurelyforyour
addon,soyou'llneedtotakeothermeasurestodelayinitializingAceDBsinceSavedVariablesstillwon'tbeloaded.
Persistingdatavalues
Pageissafe
TotalSecurity2015
OnceyouhaveAceDBsetup,it'sfairlyeasytouse-AceDBmakes8subtablesavailable:char,realm,class,race,faction,
factionrealm,profile,andglobal.Anykeysandvaluesofeachofthesetablesispersistedforallloadsofanaddonwhosharethat
subtable.Forinstance,anythingintherealmsubtablewillbepersistedforallloadsoftheaddonbyanycharactersonthesame
realm.Mostofthesubtablenamesareself-explanatory(factionrealmissimilartorealm,butlimitedtoasinglefaction,eitherAlliance
orHorde).Theonlyrealexceptionistheprofilesubtable,whichallowsaccesstouser-selectableprofiles.
function MyAddon:MyFunction()
self.db.char.myVal = "My character-specific saved value"
self.db.global.myOtherVal = "My global saved value"
end
Workingwithprofiles
Profilesallowyoutoeasilyswapbetweensetsofsavedvaluesinthedb.profilesubtable.Tosettheactiveprofile,simplyusethe
SetProfile()methodofthedbobject:
db:SetProfile("NewActiveProfile")
YoucangetthecurrentlyactiveprofileviatheGetCurrentProfile()method,orgetatableofnames(integer-indexed)andcountofall
existingprofilesviatheGetProfiles()method:
activeProfile = db:GetCurrentProfile()
possibleProfiles, numProfiles = db:GetProfiles()
Otheravailableprofilefunctionsincludingcopying,deleting,andresettingprofiles-seetheAceDB-3.0documentationformore
information.
UsingAceDBOptions-3.0
AceDBOptionsprovidesaquickwaytointegrateprofilemanagementintoanaddonusingAceDBandAceConfig,withouthavingto
worryaboutSetProfile/GetProfiles.Itcanbesetupviaasinglefunctioncall,whichreturnsatablewhichcanbeincludedintothe
optionstablepassedtoAceConfig:
options.args.profile = LibStub("AceDBOptions-3.0"):GetOptionsTable(db)
YoucancallthisrightbeforeyoupassyouroptionstabletoAceConfig:dbisthenameofyourdatabaseobjectfromAceDB,andin
thiscaseoptions.args.profilewouldbewhereinyouroptionstableyouwishthe"profile"command(andsubcommands)toreside.
Note:Theoptionstablegeneratedissharedbetweenalladdonsthatuseit,donotchangeit!
UsingAceEvent-3.0
IncludingAceEventfunctionality
TherecommendedmethodforutilizingAceEventisasamixin,likeso:
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0")
http://www.wowace.com/addons/ace3/pages/gettingstarted/
3/8
3/7/2016
Ace3GettingStartedWoWAddOnsWowAce
Ifyou'renotusingAceAddon,youcanstillembedAceEventinanobject/tableviaAceEvent'sEmbed()function:
LibStub("AceEvent-3.0"):Embed(MyObject)
Ifyoureallydon'twanttoembedAceEvent'smethodsinyourobjects,youcangetaseparateAceEventobject:
local AceEvent = LibStub("AceEvent-3.0")
However,bynotembeddingyoulosesomefunctionalitysuchasautomaticderegisteringofeventsupondisableandbettererror
reporting.Allofthefollowingexampleswillassumeyou'reembeddingAceEvent,butifyou'renot,justreplaceMyAddon:function
withAceEvent.functionandtheyshouldstillwork-thoughyoumayneedtoprovideanextraargumentortwo(seetheAceEvent-3.0
docsformoredetails).
Subscribingtoevents
Atitssimplest,allthatneedstobedonetosubscribetoagiveneventisthis:
MyAddon:RegisterEvent("NAME_OF_EVENT")
Thiswillregisteryouraddontoreceiveeventswiththegivenname,andattempttocallMyAddon:NAME_OF_EVENT()toprocess
them.
function MyAddon:NAME_OF_EVENT()
-- process the event
end
YoucanalsospecifyahandlerfunctionormethodnameinsteadoflettingAceEventlookforthedefaultmethodnames:
MyAddon:RegisterEvent("NAME_OF_EVENT", "MyHandlerMethod")
function MyAddon:MyHandlerMethod()
-- now handle it!
end
MyAddon:RegisterEvent("NAME_OF_OTHER_EVENT", function() doSomethingSpiffy() end
Theaboveexamplesdiscardanyargumentspassedtotheevent.Ifyouwanttohaveaccesstothem,justincludetheargument
specificationsinyourhandlerdefinition.However,notethatthefirstargumentpassedtoanyhandlerfunctionisalwaysthenameof
theevent,andthentheargumentsfortheeventcomeafterthat:
function MyAddon:NAME_OF_EVENT(eventName, arg1, arg2, arg3)
-- do some stuff
end
function MyAddon:NAME_OF_OTHER_EVENT(eventName, ...)
-- do some more stuff
end
Sending/receivinginter-addonmessages
AceEventalsoprovidessupportfor"messages",whicharebasicallylikeeventsexceptinsteadofbeingtriggeredbytheWoWclient,
they'retriggeredbyotheraddons.Thisisusefulifyouhavemultipleaddonswhichneedtotalktoeachother.Messagesare
subscribedtoverysimilarlytoevents(andthealternateoptionsforspecifyinghandlersworkforRegisterMessage,too):
MyAddon:RegisterMessage("NAME_OF_MESSAGE")
function MyAddon:NAME_OF_MESSAGE()
-- handle the message
end
Sendingmessagestootheraddonsisjustassimple:
MyAddon:SendMessage("NAME_OF_MESSAGE")
MyAddon:SendMessage("NAME_OF_OTHER_MESSAGE", arg1, arg2)
Notethatmessagesareonlyforaddonsrunningonthesameclient!Ifyouwanttosendmessagesbetweenvariousplayers
andtheiraddons,you'llwanttouseAceComm.
UsingAceComm-3.0
IncludingAceCommfunctionality
AswithAceEvent,AceCommcanbemixedin,embedded,orcalledasaseparateobject.Examplesofeach(pickone):
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceComm-3.0")
LibStub("AceComm-3.0"):Embed(MyObject)
local AceComm = LibStub("AceComm-3.0")
AlsoaswithAceEvent,ifyouuseAceCommasaseparateobjectyouwilllosetheconvenienceofautomaticunregistrationand
bettererrorreporting.
Sendingmessagestootherclients
Tosendamessagetootherclient(s),usetheSendCommMessage()method.Itsbasicusagerequiresthefollowingarguments:
Parameter Description
http://www.wowace.com/addons/ace3/pages/gettingstarted/
4/8
3/7/2016
Ace3GettingStartedWoWAddOnsWowAce
prefix
Astringtagtoallowrecipientstowatchforthemessagestheywanttoreceive.Mustbeprintablecharactersonly
(\032-\255).
text
Theactualdatatosendinastring,canbecontainanycharactersexceptnil(\000).Lengthisnotanissue,datatoo
longtobesentinasinglecommmessagewillautomaticallybesplitandreassembledontheotherend.
distribution
Whichchanneltosendthemessageto.Availablechannelsare"PARTY","RAID","BATTLEGROUND","GUILD",
and"WHISPER".
target
Onlyapplicableifdistribution="WHISPER",thisstringisthenametosendthemessageto:"Name"or"NameRealm".
Receivingmessagesfromotherclients
Toreceivemessages,youraddonneedstoregisteritselfaslisteningfortheprefixofthemessagesitwishestoreceive.Thisisdone
viatheRegisterComm()method.
MyAddon:RegisterComm("prefix")
Bydefault,AceCommwillattempttocallanOnCommReceivedmethodofyouraddonobject.Youcanalsospecifyahandlervia
eithermethodnameorfunctionreferenceasthesecondargumenttoRegisterComm():
MyAddon:RegisterComm("prefix2", "MySecondCommHandler")
MyAddon:RegisterComm("prefix3", function() prefixthree() end)
Thehandlerispassed4arguments,identicaltothosepassedtoSendCommMessageexceptinsteadof"target",the4thargumentis
astringcontainingthesenderofthemessage(includedregardlessofthedistributiontype).
function MyAddon:OnCommReceived(prefix, message, distribution, sender)
-- process the incoming message
end
UsingAceHook-3.0
IncludingAceHookfunctionality
LikeotherAcelibraries,AceHookisbestusedasamixin,becauseyoudon'twanttoleavehookssittingaroundiftheuserdecides
todisableyouraddon.
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceHook-3.0")
Hookingfunctions
Therearetwocommonmethodsofhookingafunction:pre-hook(regular)andpost-hook(secure).Pre-hooksarecalledbeforeand
sometimesinplaceofthefunctionwhichisbeinghooked,andinthecaseof"raw"pre-hooksrelyonthehookhandlertocallthe
originalfunctionasitdeemsnecessary(thedefaultnon-rawor"failsafe"hooksinAce3willautomaticallycalltheoriginalfunction
aftertheyfinish).Securehooks,ontheotherhand,areexecutedafterthehookedfunctionhasbeenrun,andthereturnvaluesof
theaddon-designatedhandlerforthesecurehookarediscarded.Securehooksarenecessarytoavoidtaintingexecutionpaths
whenhookingprotectedelementsoftheBlizzardUI(see[http://www.wowwiki.com/Secure_Execution_and_Taintinghere]formore
detailsregardingtainting).
Standardhooking
AstandardhookisplacedusingtheHook()methodofAceHook,typicallymixedintotheaddonobject.Thefunctiontobehooked
canbespecifiedasafunctionname(forAPIfunctions)orasanobjectandmethodnamepair.
MyAddon:Hook("APIFunctionName")
MyAddon:Hook(TargetObject, "TargetMethod")
Bydefault,AceHookwillredirectthecalltoyouraddon'sobjectwithanidenticallynamedmethodtotheoriginalfunctioncall:
function MyAddon:APIFunctionName(...)
-- handle whatever we want to do before the hooked function is called
end
Ifyouwanttocallsomeotherfunctioninstead,youcanspecifyahandler.Thefirsttwoexamplesbelowwillcallthefunction
handlerFunc(),thethirdwillcallMyAddon:handlerMethod():
MyAddon:Hook("APIFunctionName", handlerFunc)
MyAddon:Hook(TargetObject, "TargetMethod", handlerFunc)
MyAddon:Hook("APIFunctionName", "handlerMethod")
Ifyouwanttopre-hookanormallysecurefunction,butdon'tmindtaintingit,youcanaddtrueattheendoftheargumentlistto
overrideAceHook'snormalsafetycheck.Thiswilltainttheexecutionpath,however:
MyAddon:Hook("APISecureFunctionName", handlerFunc, true)
Rawhooking
Bydefault,hooksmadeusingAce3willautomaticallycalltheoriginallyhookedfunctionasnormalwithitsoriginalargumentsafter
yourhookhandlerhasrun.If,however,youwishtoeitherchangetheargumentstotheoriginalfunctionwithyourhookhandler,or
perhapsnotevenruntheoriginalfunctionatall,you'llneedtosetarawhookinstead.
Settingarawhookasthesameoptionsassettingaregularhook,butusesRawHook()instead:
MyAddon:RawHook("APIFunctionName")
http://www.wowace.com/addons/ace3/pages/gettingstarted/
5/8
3/7/2016
Ace3GettingStartedWoWAddOnsWowAce
MyAddon:RawHook(TargetObject, "TargetMethod")
Remember,ifyousetarawhookyouneedtocalltheoriginalhookedfunctionyourselfunlessyoudon'twantittorunatall!Also,as
withHook(),addingtrueasafinalargumentwilloverrideAceHook'ssecurefunctionchecking,ifyouwanttorawpre-hookasecure
function.
Thehandlerfunctionwouldlooksomethinglikethis:
-- for direct function hooks
function MyAddon:APIFunctionName(...)
-- call the original function through the self.hooks table
self.hooks["APIFunctionName"](...)
end
-- for object hooks
function MyAddon:TargetMethod(object, ...)
-- call the original function through the self.hooks table
self.hooks[object]["TargetMethod"](object, ...)
end
Youcanalsodecidewhichvaluetoreturn,eitherbydirectlyreturningtheresultoftheoriginalfunction,orreturningyourownvalue.
Securehooking
Securepost-hookingalsohasasimilarsyntaxtoregularhooking;justrememberthatyourhandlerfunctionisbeingcalledafterthe
hookedfunctionhasrun,andanythingyoureturnwillbeignored.
MyAddon:SecureHook("APISecureFunctionName")
Hookingscripts
Hookingframescriptsisquitesimilartohookingfunctions,butinsteadofcallingHook()oritsvariantsandspecifyingthefunctionto
hook,youcallHookScript()itsvariantsandspecifytheframeandthescript:
MyAddon:HookScript(TargetFrame, "ScriptName")
Aswithnon-scripthooks,thedefaulthandlerisamethodofyouraddonobjectwiththesamenameasthehookedscript.
Rawandsecureversionofscripthookingarealsoavailable:
MyAddon:RawHookScript(TargetFrame, "ScriptName")
MyAddon:SecureHookScript(TargetFrame, "ScriptName")
Checkingtoseeifsomethingisalreadyhooked
TheIsHooked()methodallowsyoutocheckifafunctionisalreadyhooked.AswithHook(),youcanspecifyeitherafunction
referenceoranobjectandmethodnamepair.Itreturnstwovalues,thefirstasimplebooleanforwhetherAceHookhasahookin
place,andthesecondareferencetothehandlerspecifiedforthathook(ifitexists-nilifnot).
hookexists, hookhandler = MyAddon:IsHooked("APIFunctionName")
UsingAceLocale-3.0
Registeringtranslations
Settingupagivenlocale'stranslationsisquitesimplewithAceLocale.Tobeginwith,createanewLuafileforthelocale-it's
recommendedthatthisincludethelocalenameforeaseofreference,butit'snotarequirement.
You'llneedtoaddthisnewfiletoyouraddon'sTOCfile,andmakesureitcomesbeforeyourmaincodefiles-otherwise,itmight
notbeloadedbeforeyourcodeistryingtouseit!
Atthebeginningofthenewfile,fetchanewlocalesetfromAceLocale:
local L = LibStub("AceLocale-3.0"):NewLocale("MyAddon", "enUS", true)
ThefirstargumenttoNewLocaleisthenameofyouraddon(mustbeconsistentacrossalllocales,sothatAceLocalecanassociate
themwithyouraddon).Thesecondisthelocaleidentifier(commononesareenUS,deDE,frFR,koKR,ruRU,zhCN,andzhTW-the
europeanenglishclientisenGB,butAceLocaleautomaticallyloadstheenUSentriesforenGB).Thefinalargumentisaboolean
valuespecifyingwhetherthelocaleyou'redefiningshouldbethedefaultlocale.Formostaddons,thiswillprobablybetrueforenUS
andfalseforeveryotherlocale.
Afteryou'vefetchedthelocaleobject,it'sjustamatterofsettingupthetableoftranslations:
if L then
L["identifier"] = "Translation for that identifier"
L["something"] = "Translation for something"
end
TheifblockispresentbecauseAceLocalewillreturnanilobjectifyou'vealreadydefinedthelocaleyourequestedanobjectforthispreventsproblemsifyouaccidentallytrytodefinetranslationsforagivenlocaletwice.
Usingtranslations
Inyourmaincodefile(Core.luaorwhateveryou'venamedit),askAceLocaletogiveyouthepropertranslationobject:
local L = LibStub("AceLocale-3.0"):GetLocale("MyAddon", true)
Thefirstargumentisthesameaddonnamethatyouspecifiedinyourlocalefile(s).Thesecondisabooleanvaluespecifying
whetherAceLocaleshouldfailsilentlyiflocaleinformationisfoundornot.truemeansnoerrormessagewillbedisplayediflocale
infocannotbeloaded.
Afteryou'veacquiredthetranslationobject,it'sjustamatterofsubstitutingitinwhereveryoupreviouslywouldhaveusedthepre-
http://www.wowace.com/addons/ace3/pages/gettingstarted/
6/8
3/7/2016
Ace3GettingStartedWoWAddOnsWowAce
localizationstring:
function MyAddon:MyFunction()
self:Print(L["identifier"])
if userinput == L["something"] then
doSomething()
end
end
Mixed-invariables
Ifyouwanttousetextelementsmixedwithvariablesfordifferentoutputyoucanalsousefunctionsinyourlocaletable.Sotheword
ortextelementorderdoesnotmatterinyourscriptandtranslationswillsoundmorenatural.
-- enUS/enGB:
L['Added X DKP to player Y.'] = function(X,Y)
return 'Added ' .. X .. ' DKP for player ' .. Y .. '.';
end
-- deDE:
L['Added X DKP to player Y.'] = function(X,Y)
return X .. ' DKP f\195\188r Spieler ' .. Y .. ' hinzugef\195\188gt.';
end
-- script.lua:
self:Print(L['Added X DKP to player Y.'](dkp_value, playername));
UsingAceSerializer-3.0
IncludingAceSerializerfunctionality
AswiththeotherAce3modules,AceSerializer-3.0canbeusedasamixinorasaseparateobject.
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceSerializer-3.0")
Serializingdataforoutput
Toobtainaserializedstringrepresentationofyourdata,justcalltheSerialize()methodwithallofthevaluesyouwanttoserialize:
MyVal1 = 23
MyVal2 = "some text"
MyVal3 = {"foo", 42, "bar"}
serializedData = MyAddon:Serialize(MyVal1, MyVal2, MyVal3)
Loadingdatafromaserializedstring
Togetthedatathatwasserializedintoastringback,calltheDeserialize()methodandpassittheserializeddatastring.Itwillreturn
multiplevalues:thefirstisalwaysabooleanindicatingsuccess(true)orfailure(false).Ifsuccessful,therestofthereturnedvalues
willbetheoriginalserializeddataitemsinthesameorderinwhichtheywerepassedtoSerialize().Ifunsuccessful,the2nd(and
onlyother)valuereturnedwillbeamessageindicatingthereasonforfailure.
success, MyVal1, MyVal2, MyVal3 = MyAddon:Deserialize(serializedData)
if not success then
-- handle error
end
Youmustlogintopostacomment.Don'thaveanaccount?Registertogetone!
5comments
AsherLT19gaming
Oct26,2013at04:03-0likes
howcanidothat?
staticharge13
May26,2013at15:57-0likes
ThisonlyhappenswhenIuseIceLancewithFingersofFrostproc.Itdoesn'thappenifIuseIceLancewithoutthe
proc.
Message:[ADDON_ACTION_BLOCKED]AddOn"Ace3"triedtocalltheprotectedfunction
"OverrideActionBarButton2:Show()".Time:05/25/1311:43:49Count:2Stack:[C]:infunction`Show'
Interface\FrameXML\ActionButton.lua:268:infunction`ActionButton_Update'
Interface\FrameXML\ActionButton.lua:523:infunction`ActionButton_OnEvent'
Interface\FrameXML\ActionButton.lua:124:infunction<Interface\FrameXML\ActionButton.lua:117>
Locals:<none>
MyactionbarsareBartender4.
Savaena
Feb17,2012at14:19-0likes
Yeah,I'mworkingwithanaddonrightnowthatwillneedtouseAceTimers-3.0andI'dliketoseethatsectionadded
hereplease!
Jeania
http://www.wowace.com/addons/ace3/pages/gettingstarted/
7/8
3/7/2016
Ace3GettingStartedWoWAddOnsWowAce
Apr14,2009at19:42-0likes
okaythisisprobablygoingtosounddumb,butI'mgoingtochanceit:p
Ihavemanymanyaddons,soIendedupwithAce2andAce3.Iamunsurehowever,whetherdisablingAce2from
loadingwillpreventanyproblems,andifso,what.AndI'mnotsurewhethertoturnitofftocheck,ortouninstallAce2.
Anyhelp,suggestionswouldbegreat^_^
merah
Feb9,2009at04:17-0likes
missingAceTimer-3.0infos
5comments
BacktoTop
MORE
FeaturedSites
Curseisthe#1Resourceforcoreonlinegamers.
NotaMember?
GetyourFreeAccount!
SignupforFree!
GuildWars2Guru
LoLPro
MMOChampion
GW2DB
Thelatestandgreatest
onTyria.
DominatewithProLoL
guides.
Keepaheadwiththe
championsofWoW
coverage.
ExploreTyriawithCurse
andGW2DB.
Browse
Core
Curse
MMOChampion
WowStead
Community
CurseForge
WowAce
SkyrimForge
Database
SC2Mapster
LoLPro
ExilePro
Wiki
http://www.wowace.com/addons/ace3/pages/gettingstarted/
8/8