在桌子内附上金属桌子
attaching metatables within tabes
我有解析配置文件并生成 table.
的解析器
结果 table 可能类似于:
root = {
global = {
},
section1 = {
subsect1 = {
setting = 1
subsubsect2 = {
}
}
}
}
目标是有一个 table 我可以从中读取设置,如果设置不存在,它会尝试从它的父项中获取它。在顶层,它将从全球范围内获取。如果它不在全球范围内,它将 return nil。
我像这样将 metatables 附加到根:
local function attach_mt(tbl, parent)
for k,v in pairs(tbl) do
print(k, v)
if type(v) == 'table' then
attach_mt(v, tbl)
setmetatable(v, {
__index = function(t,k)
print("*****parent=", dump(parent))
if parent then
return tbl[k]
else
if rawget(tbl, k) then
return rawget(tbl, k)
end
end
print(string.format("DEBUG: Request for key: %s: not found", k))
return nil
end
})
end
end
end
attach_mt(root)
但是,在请求密钥时它不起作用。情况似乎总是零。我如何从父 table 读取?
local function attach_mt(tbl, parent)
setmetatable(tbl, {__index = parent or root.global})
for k, v in pairs(tbl) do
if type(v) == 'table' then
attach_mt(v, tbl)
end
end
end
attach_mt(root)
setmetatable(root.global, nil)
我有解析配置文件并生成 table.
的解析器结果 table 可能类似于:
root = {
global = {
},
section1 = {
subsect1 = {
setting = 1
subsubsect2 = {
}
}
}
}
目标是有一个 table 我可以从中读取设置,如果设置不存在,它会尝试从它的父项中获取它。在顶层,它将从全球范围内获取。如果它不在全球范围内,它将 return nil。
我像这样将 metatables 附加到根:
local function attach_mt(tbl, parent)
for k,v in pairs(tbl) do
print(k, v)
if type(v) == 'table' then
attach_mt(v, tbl)
setmetatable(v, {
__index = function(t,k)
print("*****parent=", dump(parent))
if parent then
return tbl[k]
else
if rawget(tbl, k) then
return rawget(tbl, k)
end
end
print(string.format("DEBUG: Request for key: %s: not found", k))
return nil
end
})
end
end
end
attach_mt(root)
但是,在请求密钥时它不起作用。情况似乎总是零。我如何从父 table 读取?
local function attach_mt(tbl, parent)
setmetatable(tbl, {__index = parent or root.global})
for k, v in pairs(tbl) do
if type(v) == 'table' then
attach_mt(v, tbl)
end
end
end
attach_mt(root)
setmetatable(root.global, nil)