From 0365e1bb27e6bedcba4b9b62baaa08d60115ca9a Mon Sep 17 00:00:00 2001 From: Daniel Silverstone Date: Thu, 23 Aug 2012 11:29:32 +0100 Subject: Reading of settings back now works --- examples/simple-config-reader.lua | 6 +++++- lib/clod.lua | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/examples/simple-config-reader.lua b/examples/simple-config-reader.lua index b1b4719..823d285 100644 --- a/examples/simple-config-reader.lua +++ b/examples/simple-config-reader.lua @@ -12,7 +12,11 @@ project.name "Clod" project.head "refs/heads/master" ]] -conf = clod.parse(configuration) +conf, err = clod.parse(configuration) +if not conf then + error(err) +end print("Project name is", conf.settings["project.name"]) print("Project HEAD is", conf.settings.project.head) +print("Unknown entry is", conf.settings.project.isnil) diff --git a/lib/clod.lua b/lib/clod.lua index d25048b..7058ab3 100644 --- a/lib/clod.lua +++ b/lib/clod.lua @@ -12,12 +12,47 @@ local loadstring = loadstring local tconcat = table.concat local setmetatable = setmetatable local setfenv = setfenv +local pairs = pairs -- metatable for clod config operations local clod_mt = {} -- metadata for clod config instances local metadata = setmetatable({}, {__mode = "k"}) +-- metatable for settings objects +local settings_mt = {} +local gen_settings + +function settings_mt:__index(subkey) + local meta = metadata[self] + local confmeta = metadata[meta.conf] + local key = subkey + if meta.prefix then + key = meta.prefix .. "." .. subkey + end + if confmeta.settings[key] then + return confmeta.settings[key].value + end + for k in pairs(confmeta.settings) do + if k:sub(1,#key) == key then + return gen_settings(self, key) + end + end +end + +-- Helper routines +function gen_settings(tab, prefix) + local meta = metadata[tab] + local clodconf = meta.conf or tab + local newmeta = { + conf = clodconf, + prefix = prefix + } + local ret = setmetatable({}, settings_mt) + metadata[ret] = newmeta + return ret +end + -- Methods for clod instances local methods = {} -- cgit v1.2.1