Talk:Creating defaults

From Warcraft Wiki
Jump to navigation Jump to search

Idea for your "Advanced Default Setting Updating"

I just used the already given method of updating defaults for some time, but began feeling tired of the unflexibility and size of this code. So I decided to work out my own and ask you, what you think of it.


This code let us traverse all (sub-)tables of our settings (= database) and take over values that can be used in future (if the base-structure of the table hasn't changed) So there is no need to stretch our code any further for every sub-sub-sub-....table we add to the settings/defaults.


Here we go:

function YourAddon_UpdateDB(newDB, oldDB)
   local k, v;
   for k, v in pairs(newDB) do
      if (type(v) == "table") then
         if (oldDB and oldDB[k] ~= nil) then
            newDB[k] = YourAddon_UpdateDB(v, oldDB[k]);
         end
      elseif (oldDB and oldDB[k] ~= nil and k ~= "version") then
         newDB[k] = oldDB[k];
      end
   end
   return newDB;
end


And here what the code is used to be, step by step:

function YourAddon_UpdateDB(the defaultDB [used as "the base" for the newDB], the DB to check against the defaults)
   local k, v;
   -- Moving through every Key(k) in de defaultDB
      -- If the type of Value(v) is "table" ...
         -- If the Key exists in the oldDB ...
            -- Call self and submit the subtables to traverse them
         end
      -- Elseif Key exists in oldDB and isn't called "version" (we don't want to take over the old version#) ...
         -- Take the Value of the oldDB into the newDB
      end
   end
   -- Return the newDB to the caller
end


Calling this method could be looking like this:

if (not YourAddonDB["version"] or YourAddonDB["version"] ~= defaultDB["version"]) then
   YourAddonDB = YourAddon_updateDB(defaultDB, YourAddonDB);
end


That's all folks.

Flamecore (talk) 10:21, December 15, 2009 (UTC)