From 57adb49de2c7fc4ca311a569c69e07ed20cefc9a Mon Sep 17 00:00:00 2001
From: Matthias Schiffer <mschiffer@universe-factory.net>
Date: Tue, 8 Aug 2017 13:20:38 +0200
Subject: [PATCH] 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')
---
 .../luasrc/usr/lib/lua/gluon/site.lua         | 42 +++++++++++++++++++
 1 file changed, 42 insertions(+)
 create mode 100644 package/gluon-core/luasrc/usr/lib/lua/gluon/site.lua

diff --git a/package/gluon-core/luasrc/usr/lib/lua/gluon/site.lua b/package/gluon-core/luasrc/usr/lib/lua/gluon/site.lua
new file mode 100644
index 000000000..1c7803f11
--- /dev/null
+++ b/package/gluon-core/luasrc/usr/lib/lua/gluon/site.lua
@@ -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)
-- 
GitLab