Recipe Master

Recipe Master

9.3k Downloads

De-globalization

Road-block opened this issue ยท 2 comments

commented

Good value in the addon for users, but it would really benefit from avoiding all the functions and variables put into the global namespace.

This is a bad practice for addons as it can lead to very hard to debug side-effects when they can overwrite or get overwritten by other addons (or the default interface code).

There is a construct you can use to share variables/methods within your addon while keeping your addon from "polluting" the global namespace.
The WoW Client passes a vararg ... to every lua file loaded by the addon's .toc file (either directly or through xml).
That vararg contains 2 arguments the addonName as a string and a table that is scoped to your addon files only

Example code.

local addonName, addon = ... -- top of \Source/Initialization.lua
--
addon.character = UnitName("player")
addon.server = GetRealmName()
--
function addon:createRecipeMasterSavedVariables()
    if not RecipeMasterProfessionsAndSkills then
        RecipeMasterProfessionsAndSkills = {}
    end
    if not RecipeMasterPreferences then
        RecipeMasterPreferences = defaultPreferences
    end
end

Same treatment for all the unnecessary globals in that file.
Now let's assume you want to refer to character or server in another addon file

You simply need the same
local addonName, addon = ... at the top and you have access to addon table with all the variables and functions tucked neatly inside.

You would also want to re-arrange loading order in .toc
Intialization, Localization etc first, then databases and so on.
Example refactoring of Localization.lua

local addonName, addon = ...
local L = {}
addon.L = L
if locale == "enUS" then
    L.professionNames = {
        [171] = "Alchemy",
        [164] = "Blacksmithing",
        [185] = "Cooking",
        [333] = "Enchanting",
        [202] = "Engineering",
        [129] = "First Aid",
        [356] = "Fishing",
        [773] = "Inscription",
        [755] = "Jewelcrafting",
        [165] = "Leatherworking",
        [186] = "Mining",
        [197] = "Tailoring"
    }
    L.recipePrefixes = {"Recipe: ", "Plans: ", "Formula: ", "Schematic: ", "Pattern: ", "Manual: "}
    return
-- similar for rest of file

Any other file that needs access to localized entries

local addonName, addon = ...
local L = addon.L

-- L.recipePrefixes now available in this file scope
commented

Hello, Road-block.

Thank you for your valuable feedback!
That is something that caused me an issue before but I wasn't sure on how to deal with it effectively. Your suggestion will be implemented ASAP.

commented

The add-on has been de-globalized and the changes have been implemented in version Vanilla 1.0.1.
Your help is greatly appreciated, @Road-block !