Improving code

Leandro Silva [10-05-18 - 20:41]
Improving code
Filename
LeoAltholic.lua
LeoAltholicUI.lua
diff --git a/LeoAltholic.lua b/LeoAltholic.lua
index 691fd45..962676b 100644
--- a/LeoAltholic.lua
+++ b/LeoAltholic.lua
@@ -4,6 +4,7 @@ LeoAltholic.name = "LeoAltholic"
 LeoAltholic.displayName = "Leo's Altholic"
 LeoAltholic.version = "1.1.3"
 LeoAltholic.chatPrefix = "|c39B027" .. LeoAltholic.name .. "|r: "
+
 LeoAltholic.timerQueue = {}
 LeoAltholic.charList = {}
 LeoAltholic.myself = nil
@@ -14,7 +15,7 @@ LeoAltholic.jewelryMaxTraits = select(3,GetSmithingResearchLineInfo(7,1))
 LeoAltholic.panelList = { "Bio", "Stats", "Skills", "Champion", "Tracked", "Inventory", "Research" }
 LeoAltholic.craftResearch = {CRAFTING_TYPE_BLACKSMITHING,CRAFTING_TYPE_CLOTHIER,CRAFTING_TYPE_WOODWORKING,CRAFTING_TYPE_JEWELRYCRAFTING}

-function LeoAltholic.loadPlayerDataPart(skillType, baseElem)
+local function loadPlayerDataPart(skillType, baseElem)
     if skillType == nil then
         return
     end
@@ -63,9 +64,39 @@ function LeoAltholic.loadPlayerDataPart(skillType, baseElem)
     end
 end

-function LeoAltholic.InitCharsList()
+local function createQuestEntry(questId)
+    local questName,backgroundText,activeStepText,activeStepType, activeStepTrackerOverrideText, completed, tracked, questLevel,pushed,questType,instanceDisplayType = GetJournalQuestInfo(questId)
+    local repeatType = GetJournalQuestRepeatType(questId)
+    local locationInfo
+    if questType == QUEST_TYPE_GUILD then
+        locationInfo = "Guild"
+    elseif questType == QUEST_TYPE_MAIN_STORY then
+        locationInfo = "Main Story"
+    else
+        locationInfo = GetJournalQuestLocationInfo(questId)
+    end
+    local quest = {
+        name = questName,
+        backgroundText = backgroundText,
+        activeStepText = activeStepText,
+        activeStepType = activeStepType,
+        activeStepTrackerOverrideText = activeStepTrackerOverrideText,
+        questLevel = questLevel,
+        questType = questType,
+        instanceDisplayType = instanceDisplayType,
+        location = locationInfo,
+        repeatType = repeatType,
+        isDaily = repeatType == QUEST_REPEAT_DAILY
+    }
+    return quest
+end
+
+local function initCharsList()
+
     if LeoAltholic.savedVariables.CharList == nil then LeoAltholic.savedVariables.CharList = {} end

+    LeoAltholic.CharName = GetUnitName("player")
+
     local function getStat(stat) return GetPlayerStat(stat, STAT_BONUS_OPTION_APPLY_BONUS, STAT_SOFT_CAP_OPTION_APPLY_SOFT_CAP) end

     local numChars = GetNumCharacters()
@@ -103,7 +134,6 @@ function LeoAltholic.InitCharsList()
         end
     end

-    LeoAltholic.CharName = GetUnitName("player")
     LeoAltholic.CharNum = 0
     local char = LeoAltholic.savedVariables.CharList[LeoAltholic.CharName] or {
         bio = {},
@@ -213,48 +243,48 @@ function LeoAltholic.InitCharsList()
     local skillType = SKILL_TYPE_ARMOR
     char.skills.armor = {}
     local baseElem = char.skills.armor
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     --
     skillType = SKILL_TYPE_WORLD
     char.skills.world = {}
     baseElem = char.skills.world
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     --
     skillType = SKILL_TYPE_CLASS
     char.skills.class = {}
     baseElem = char.skills.class
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     --
     skillType = SKILL_TYPE_GUILD
     char.skills.guild = {}
     baseElem = char.skills.guild
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     --
     skillType = SKILL_TYPE_RACIAL
     char.skills.racial = {}
     baseElem = char.skills.racial
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     --
     skillType = SKILL_TYPE_WEAPON
     char.skills.weapon = {}
     baseElem = char.skills.weapon
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     --
     skillType = SKILL_TYPE_AVA
     char.skills.ava = {}
     baseElem = char.skills.ava
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     skillType = SKILL_TYPE_TRADESKILL
     char.skills.craft = {}
     baseElem = char.skills.craft
-    LeoAltholic.loadPlayerDataPart(skillType,baseElem)
+    loadPlayerDataPart(skillType,baseElem)

     local function GetBonus(craft)
         local skillType0, skillId = GetCraftingSkillLineIndices(craft)
@@ -357,49 +387,23 @@ function LeoAltholic.InitCharsList()
     local n = 0
     for i = 1, MAX_JOURNAL_QUESTS do
         if IsValidQuestIndex(i) then
-            local quest = LeoAltholic.createQuestEntry(i)
+            local quest = createQuestEntry(i)
             table.insert(char.quests.actives, quest)
             n = n + 1
         end
     end
-    --char.achievements = LeoAltholic.CreateCharDataAchievements()
+    --char.achievements = createCharDataAchievements()

     LeoAltholic.savedVariables.CharList[LeoAltholic.CharName] = char
 end

-function LeoAltholic.todayReset()
+function LeoAltholic.TodayReset()
     local diff = zo_floor(GetDiffBetweenTimeStamps(GetTimeStamp(), 1538200800) / 86400)
     return 1538200800 + (diff * 86400)
 end

-function LeoAltholic.createQuestEntry(questId)
-    local questName,backgroundText,activeStepText,activeStepType, activeStepTrackerOverrideText, completed, tracked, questLevel,pushed,questType,instanceDisplayType = GetJournalQuestInfo(questId)
-    local repeatType = GetJournalQuestRepeatType(questId)
-    local locationInfo
-    if questType == QUEST_TYPE_GUILD then
-        locationInfo = "Guild"
-    elseif questType == QUEST_TYPE_MAIN_STORY then
-        locationInfo = "Main Story"
-    else
-        locationInfo = GetJournalQuestLocationInfo(questId)
-    end
-    local quest = {
-        name = questName,
-        backgroundText = backgroundText,
-        activeStepText = activeStepText,
-        activeStepType = activeStepType,
-        activeStepTrackerOverrideText = activeStepTrackerOverrideText,
-        questLevel = questLevel,
-        questType = questType,
-        instanceDisplayType = instanceDisplayType,
-        location = locationInfo,
-        repeatType = repeatType,
-        isDaily = repeatType == QUEST_REPEAT_DAILY
-    }
-    return quest
-end

-function LeoAltholic.ParseAchievementLinkId(link)
+local function parseAchievementLinkId(link)

     if (link == nil or link == "") then
         return -1, 0, 0
@@ -414,7 +418,7 @@ function LeoAltholic.ParseAchievementLinkId(link)
     return achId, tonumber(achData), tonumber(achTimestamp)
 end

-function LeoAltholic.CreateCharDataAchievements()
+local function createCharDataAchievements()
     local achievements = {}
     local numTopLevelCategories = GetNumAchievementCategories()
     local countCategory = 1
@@ -457,7 +461,7 @@ function LeoAltholic.CreateCharDataAchievements()

                         while (currentId ~= nil and currentId > 0) do
                             local achLink = GetAchievementLink(currentId)
-                            local _, progress, timestamp = LeoAltholic.ParseAchievementLinkId(achLink)
+                            local _, progress, timestamp = parseAchievementLinkId(achLink)

                             if (progress ~= 0 or timestamp ~= 0) then
                                 achievements[countCategory].subCategory[countSub].achievements[countAchiev] = {
@@ -547,19 +551,10 @@ function LeoAltholic.log(message)
 end

 function LeoAltholic.GetMyself()
-    if LeoAltholic.myselfIndex > 0 then
-        return LeoAltholic.myself
-    end
-    for i, char in ipairs(LeoAltholic.GetCharacters()) do
-        if char.bio.name == LeoAltholic.CharName then
-            LeoAltholic.myself = char
-            LeoAltholic.myselfIndex = i
-            return LeoAltholic.myself
-        end
-    end
+    return LeoAltholic.savedVariables.CharList[LeoAltholic.CharName]
 end

-function LeoAltholic:OnResearchCompleted(craft, line, trait)
+local function onResearchCompleted(eventCode, craft, line, trait)
     local myself = LeoAltholic.GetMyself()
     myself.research[craft][line][trait] = true

@@ -578,7 +573,7 @@ function LeoAltholic:OnResearchCompleted(craft, line, trait)
     end
 end

-function LeoAltholic.ProcessQueue()
+local function processQueue()
     for x,data in pairs(LeoAltholic.timerQueue) do
         if GetDiffBetweenTimeStamps(data.time, GetTimeStamp()) <= 0 then
             if data.charName ~= LeoAltholic.CharName and LeoAltholic.savedVariables.settings.completedResearch.chat == true then
@@ -594,7 +589,7 @@ function LeoAltholic.ProcessQueue()
     end
 end

-function LeoAltholic.GetTimer()
+local function createMessageQueue()
     LeoAltholic.timerQueue = {}
     for _, char in pairs(LeoAltholic.GetCharacters()) do
         if GetDiffBetweenTimeStamps(char.attributes.riding.time - GetTimeStamp()) < 0 then
@@ -632,9 +627,9 @@ function LeoAltholic.GetTimer()
     end
 end

-function LeoAltholic.OnUpdate()
+local function onUpdate()

-    LeoAltholic.ProcessQueue()
+    processQueue()

     if LeoAltholic:isHidden() then
         return
@@ -670,7 +665,7 @@ function LeoAltholic.OnUpdate()
     end
 end

-function LeoAltholic.trackQuest(questId, automatically)
+local function trackQuest(questId, automatically)
     local type = GetJournalQuestRepeatType(questId)
     if type ~= QUEST_REPEAT_DAILY then
         if automatically ~= true then
@@ -678,7 +673,7 @@ function LeoAltholic.trackQuest(questId, automatically)
         end
         return
     end
-    local quest = LeoAltholic.createQuestEntry(questId)
+    local quest = createQuestEntry(questId)
     for _,trackedQuest in pairs(LeoAltholic.savedVariables.CharList[LeoAltholic.CharName].quests.tracked) do
         if (trackedQuest.name == quest.name) then
             if automatically ~= true then
@@ -695,15 +690,15 @@ function LeoAltholic.trackQuest(questId, automatically)
     LeoAltholic.log("Tracking " .. tracked.name .. "...")
 end

-function LeoAltholic.OnQuestAdded(eventCode, journalIndex, questName, objectiveName)
-    local quest = LeoAltholic.createQuestEntry(journalIndex)
+local function onQuestAdded(eventCode, journalIndex, questName, objectiveName)
+    local quest = createQuestEntry(journalIndex)
     if quest.isDaily == false then return end
     if LeoAltholic.savedVariables.settings.tracked.allDaily == true or (quest.questType == QUEST_TYPE_CRAFTING and LeoAltholic.savedVariables.settings.tracked.dailyWrits == true) then
-        LeoAltholic.trackQuest(journalIndex, true)
+        trackQuest(journalIndex, true)
     end
 end

-function LeoAltholic.OnQuestComplete(eventCode, questName, level, previousExperience, currentExperience, rank, previousPoints, currentPoints)
+local function onQuestComplete(eventCode, questName, level, previousExperience, currentExperience, rank, previousPoints, currentPoints)
     for _,trackedQuest in pairs(LeoAltholic.savedVariables.CharList[LeoAltholic.CharName].quests.tracked) do
         if (trackedQuest.name == questName) then
             trackedQuest.lastDone = GetTimeStamp()
@@ -713,15 +708,7 @@ function LeoAltholic.OnQuestComplete(eventCode, questName, level, previousExperi
     end
 end

-function LeoAltholic.formatNumber(amount)
-    if amount == nil then return nil; end
-    if type(amount) == "string" then amount = tonumber( amount ) end
-    if type(amount) ~= "number" then return amount; end
-    if amount < 1000 then return amount; end
-    return FormatIntegerWithDigitGrouping( amount, GetString( SI_DIGIT_GROUP_SEPARATOR ) )
-end
-
-function LeoAltholic.Initialize()
+local function initialize()

     local oldVariables = ZO_SavedVars:NewAccountWide("LeoAltholicSavedVariables", 2)
     LeoAltholic.savedVariables = ZO_SavedVars:NewAccountWide("LeoAltholicSavedVariables", 2, nil, nil, GetWorldName())
@@ -755,10 +742,10 @@ function LeoAltholic.Initialize()

     LeoAltholic.RestorePosition()

-    LeoAltholic.InitCharsList()
+    initCharsList()
     LeoAltholic.InitializeCharacterFrames()
     LeoAltholic.DisplayCharacterFrames()
-    LeoAltholic.GetTimer()
+    createMessageQueue()

     if GetDisplayName() == "@LeandroSilva" then
         SLASH_COMMANDS["/rr"] = function(cmd)
@@ -779,7 +766,7 @@ function LeoAltholic.Initialize()
             visible = function() return true end,
             order = 100,
             callback = function()
-                LeoAltholic.trackQuest(QUEST_JOURNAL_MANAGER:GetFocusedQuestIndex())
+                trackQuest(QUEST_JOURNAL_MANAGER:GetFocusedQuestIndex())
             end,
         }
     }
@@ -820,42 +807,44 @@ function ZO_QuestJournalNavigationEntry_OnMouseUp(label, button, upInside)
         local questIndex = label.node.data.questIndex
         if questIndex and GetJournalQuestRepeatType(questIndex) == QUEST_REPEAT_DAILY then
             AddMenuItem("Track with " .. LeoAltholic.displayName, function()
-                LeoAltholic.trackQuest(questIndex)
+                trackQuest(questIndex)
             end)
             ShowMenu(label)
         end
     end
 end

-function LeoAltholic.NewMovementInUIMode(eventCode)
+local function onNewMovementInUIMode(eventCode)
     if not LeoAltholicWindow:IsHidden() then LeoAltholic:HideUI() end
 end

-function LeoAltholic.OnChampionPerksSceneStateChange(oldState,newState)
+local function onChampionPerksSceneStateChange(oldState,newState)
     if newState == SCENE_SHOWING then
         if not LeoAltholicWindow:IsHidden() then LeoAltholic:HideUI() end
     end
 end

-function LeoAltholic.OnPlayerDeactivated(event, addonName)
+local function onPlayerDeactivated(event, addonName)
     EVENT_MANAGER:UnregisterForEvent(LeoAltholic.Name, EVENT_PLAYER_DEACTIVATED)
-    LeoAltholic.InitCharsList()
+    initCharsList()
 end

-function LeoAltholic.OnAddOnLoaded(event, addonName)
+local function onAddOnLoaded(event, addonName)
     if addonName == LeoAltholic.name then
         EVENT_MANAGER:UnregisterForEvent(LeoAltholic.name, EVENT_ADD_ON_LOADED)
         SCENE_MANAGER:RegisterTopLevel(LeoAltholicWindow, false)
-        LeoAltholic.Initialize()
+        initialize()
+
+        EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_PLAYER_DEACTIVATED, onPlayerDeactivated)
+        EVENT_MANAGER:RegisterForUpdate(LeoAltholic.name, 5000, onUpdate)
+        EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_NEW_MOVEMENT_IN_UI_MODE, onNewMovementInUIMode)
+        EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_QUEST_COMPLETE, onQuestComplete)
+        EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_QUEST_ADDED, onQuestAdded)
+        EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_SMITHING_TRAIT_RESEARCH_COMPLETED, onResearchCompleted)
+        CHAMPION_PERKS_SCENE:RegisterCallback('StateChange', onChampionPerksSceneStateChange)
+
         LeoAltholic.log("started.")
     end
 end

-EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_ADD_ON_LOADED, LeoAltholic.OnAddOnLoaded)
-EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_PLAYER_DEACTIVATED, LeoAltholic.OnPlayerDeactivated)
-EVENT_MANAGER:RegisterForUpdate(LeoAltholic.name, 5000, LeoAltholic.OnUpdate)
-EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_NEW_MOVEMENT_IN_UI_MODE, LeoAltholic.NewMovementInUIMode)
-EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_QUEST_COMPLETE, LeoAltholic.OnQuestComplete)
-EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_QUEST_ADDED, LeoAltholic.OnQuestAdded)
-EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_SMITHING_TRAIT_RESEARCH_COMPLETED, LeoAltholic.OnResearchCompleted)
-CHAMPION_PERKS_SCENE:RegisterCallback('StateChange', LeoAltholic.OnChampionPerksSceneStateChange)
+EVENT_MANAGER:RegisterForEvent(LeoAltholic.name, EVENT_ADD_ON_LOADED, onAddOnLoaded)
diff --git a/LeoAltholicUI.lua b/LeoAltholicUI.lua
index 22513fc..90cd40e 100644
--- a/LeoAltholicUI.lua
+++ b/LeoAltholicUI.lua
@@ -325,6 +325,14 @@ function LeoAltholic.TooltipSkill(control, visible, charId, line, lineId)
     end
 end

+local function formatNumber(amount)
+    if amount == nil then return nil; end
+    if type(amount) == "string" then amount = tonumber( amount ) end
+    if type(amount) ~= "number" then return amount; end
+    if amount < 1000 then return amount; end
+    return FormatIntegerWithDigitGrouping( amount, GetString( SI_DIGIT_GROUP_SEPARATOR ) )
+end
+
 function LeoAltholic.DisplayCharacterFrames()
     local control
     for _,panel in ipairs(LeoAltholic.panelList) do
@@ -433,7 +441,7 @@ function LeoAltholic.DisplayCharacterFrames()
                         end
                     end)
                     if char.quests.tracked[i].lastDone ~= nil then
-                        if char.quests.tracked[i].lastDone <= LeoAltholic.todayReset() then
+                        if char.quests.tracked[i].lastDone <= LeoAltholic.TodayReset() then
                             done:SetText("|cCB110Enot done today|r")
                         else
                             local diff = GetTimeStamp() - char.quests.tracked[i].lastDone
@@ -462,13 +470,13 @@ function LeoAltholic.DisplayCharacterFrames()
         control = row:GetNamedChild("SoulGems")
         control:SetText("|c21A121" .. char.inventory.soulGemFilled .. '|r / ' .. char.inventory.soulGemEmpty)
         control = row:GetNamedChild("Gold")
-        control:SetText(LeoAltholic.formatNumber(char.inventory.gold))
+        control:SetText(formatNumber(char.inventory.gold))
         control = row:GetNamedChild("AP")
-        control:SetText(LeoAltholic.formatNumber(char.inventory.ap))
+        control:SetText(formatNumber(char.inventory.ap))
         control = row:GetNamedChild("TelVar")
-        control:SetText(LeoAltholic.formatNumber(char.inventory.telvar))
+        control:SetText(formatNumber(char.inventory.telvar))
         control = row:GetNamedChild("Writ")
-        control:SetText(LeoAltholic.formatNumber(char.inventory.writVoucher))
+        control:SetText(formatNumber(char.inventory.writVoucher))

         row = WINDOW_MANAGER:GetControlByName('LeoAltholicResearchRow'..x)
         for _,craft in pairs(LeoAltholic.craftResearch) do