Revision: 2022
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at December 18, 2006 08:06 by kergoth
Initial Code
local mooDB
local defaults = {
a = {
foo = "bar"
},
b = 1,
c = {
bar = "foo"
},
}
if not mooDB then
-- NOTE: This would not be in the actual real world code. This
-- simulates user data, normally loaded from some sort
-- of datastore, which is SavedVariables in the case of
-- World of Warcraft.
mooDB = {
c = {
bop = "whee"
}
}
end
function inheritdefaults(t, defaults)
for k,v in pairs(defaults) do
if t[k] then
if type(v) == "table" then
inheritdefaults(t[k], v)
end
end
end
local mt = getmetatable(t) or {}
function mt:__index(k)
return defaults[k]
end
return setmetatable(t, mt)
end
inheritdefaults(mooDB, defaults)
assert(mooDB ~= defaults)
assert(mooDB.a == defaults.a)
assert(mooDB.c ~= defaults.c)
assert(mooDB.a.foo == "bar")
assert(mooDB.b == 1)
assert(mooDB.c.bar == "foo")
assert(mooDB.c.bop == "whee")
Initial URL
Initial Description
Initial Title
Lua: Sane Granular Defaults for User Supplied Data
Initial Tags
Initial Language
Other