Thread: Saved Variables
View Single Post
11-23-14, 01:10 PM   #5
cokedrivers
A Rage Talon Dragon Guard
 
cokedrivers's Avatar
AddOn Author - Click to view addons
Join Date: Aug 2009
Posts: 325
Originally Posted by Phanx View Post
Especially for something as simple as defining a saved variable, I would recommend avoiding the use of libraries until you have a decent understanding of how the system actually works first. Then, if you want to use a library for some reason (eg. to make it easier to manage separate settings profiles), it won't be a black box.

Here is the simple system I use for managing default settings in my addons:

In MyAddon.toc:
Code:
## SavedVariables: MyAddonDB
In MyAddon.lua:
Code:
-- This function gets run when the PLAYER_LOGIN event fires:
function MyAddonDB:PLAYER_LOGIN()
	-- This table defines the addon's default settings:
	local defaults = {
		x = 0,
		y = 200,
		p = "BOTTOM",
		font = {
			face = "Friz Quadrata TT",
			size = 14,
			outline = "OUTLINE",
		},
		color = {
			r = 0,
			g = 1,
			b = 1,
		}
	}

	-- This function copies values from one table into another:
	local function copyDefaults(src, dst)
		-- If no source (defaults) is specified, return an empty table:
		if type(src) ~= "table" then return {} end
		-- If no target (saved variable) is specified, create a new table:
		if type(dst) then dst = {} end
		-- Loop through the source (defaults):
		for k, v in pairs(src) do
			-- If the value is a sub-table:
			if type(v) == "table" then
				-- Recursively call the function:
				dst[k] = copyDefaults(v, dst[k])
			-- Or if the default value type doesn't match the existing value type:
			elseif type(v) ~= type(dst[k]) then
				-- Overwrite the existing value with the default one:
				dst[k] = v
			end
		end
		-- Return the destination table:
		return dst
	end

	-- Copy the values from the defaults table into the saved variables table
	-- if it exists, and assign the result to the saved variable:
	MyAddonDB = copyDefaults(defaults, MyAddonDB)
end
How would you use these defaults in your addon would it be MyAddonDB.x ?

of would this function replace your:
Code:
local cfg = MyAddonDB.defaults

MyFrame = CreateFrame("frame")
MyFrame:SetPoint(cfg.p, UIParent, cfg.x, cfg.y)
The reason I ask is I would like to get away from Ace for some of the addons im working on and if this will alow me to have a defaults like ace does then the only othe part Ill have to figure out is in-game config to change things without doing a /reload.

Thanks Coke
  Reply With Quote