Too my knowledge :
Code:
local PocketPlotDB = setmetatable(PocketPlotDB or {}, {__index = defaults})
is the same as
Code:
PocketPlotDB = PocketPlotDB or {}
local ppdb = {}
setmetatable(PocketPlotDB, ppdb)
ppdb.__index = defaults
The only difference is that in the first method PocketPlotDB is local, so I'm guessing your "PocketPlotDB is nil" error is due to variable scope. i.e.
Code:
function printvar()
print(var)
end
local var = "cat"
printvar()
would print nil.
As for your other problem of the metatable not being applied to existing substables, you could do this:
Code:
local function DeepMetatable(tbl, defaulttbl) --I couldn't think of a better name
for i, v in pairs(tbl) do
if type(v) == "table" and defaulttbl[i] then
DeepMetatable(tbl, defaulttbl[i])
end
end
return setmetatable(tbl, {__index = defaulttbl})
end
local defaults = {
color = {
r = 1,
g = 0.6,
b = 0.6
}
}
PocketPlotDB = {
color = {}
}
PocketPlotDB = DeepMetatable(PocketPlotDB or {}, defaults)
print(PocketPlotDB.color.r)
Would output 1.
Whereas the other
Code:
PocketPlotDB = setmetatable(PocketPlotDB or {}, {__index = defaults})
print(PocketPlotDB.color.r)
would give you nil.
I think the reason why the previous method I posted didn't work because the __index metatable wasn't applied to pre-existing subtables, so if those pre-existing subtables were missing values there was no __index metatable to get the default value.
Hope this helps.