gluon-core: add new gluon.site library for convenient access to optional values

The new gluon.site lua library will eventually replace gluon.site_config
(which is hereby deprecated, but will continue to be supported for a
while).

The new gluon.site library will wrap all values to allow traversing
non-existing tables without errors.

    site = require 'gluon.site'
    c = site.a.b.c -- doesn't fail even if a or a.b don't exist

The wrapped values must be unwrapped using call syntax:

    site_name = site.site_name()

Using the call syntax on a non-existing value will return nil. An
alternative default value may be passed instead:

    mac = site.next_node.mac('16:41:95:40:f7:dc')
This commit is contained in:
Matthias Schiffer 2017-08-08 13:20:38 +02:00
parent 085cf0debf
commit 57adb49de2
No known key found for this signature in database
GPG Key ID: 16EF3F64CB201D9C

View File

@ -0,0 +1,42 @@
local site = require 'gluon.site_config'
local wrap
local function index(t, k)
local v = getmetatable(t).value
if v == nil then return wrap(nil) end
return wrap(v[k])
end
local function newindex()
error('attempted to modify site config')
end
local function call(t, def)
local v = getmetatable(t).value
if v == nil then return def end
return v
end
local function _wrap(v, t)
return setmetatable(t or {}, {
__index = index,
__newindex = newindex,
__call = call,
value = v,
})
end
local none = _wrap(nil)
function wrap(v, t)
if v == nil then return none end
return _wrap(v, t)
end
module 'gluon.site'
return wrap(site, _M)