Thread: Saved Variables
View Single Post
08-30-12, 02:21 PM   #4
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
Originally Posted by Jarod24 View Post
there are also some libraries (ace?) to do this for you.
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 not 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
__________________
Retired author of too many addons.
Message me if you're interested in taking over one of my addons.
Don’t message me about addon bugs or programming questions.

Last edited by Phanx : 12-16-15 at 01:13 AM.
  Reply With Quote