forked from Liquipedia/Lua-Modules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpage_variable_namespace.lua
More file actions
79 lines (63 loc) · 1.76 KB
/
Copy pathpage_variable_namespace.lua
File metadata and controls
79 lines (63 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
---
-- @Liquipedia
-- wiki=commons
-- page=Module:PageVariableNamespace
--
-- Please see https://github.com/Liquipedia/Lua-Modules to contribute
--
local Class = require('Module:Class')
local Logic = require('Module:Logic')
local StringUtils = require('Module:StringUtils')
local Namespace = Class.new(function(self, prefix)
self.prefix = prefix
end)
function Namespace:get(key)
return StringUtils.nilIfEmpty(mw.ext.VariablesLua.var(self.prefix .. key))
end
function Namespace:set(key, value)
mw.ext.VariablesLua.vardefine(self.prefix .. key, StringUtils.nilIfEmpty(value))
end
function Namespace:delete(key)
self:set(key, nil)
end
local CachedTable = Class.new(function(self, table)
self.results = {}
self.table = table
end)
function CachedTable:get(key)
if not self.results[key] then
self.results[key] = self.table:get(key)
end
return self.results[key]
end
function CachedTable:set(key, value)
self.results[key] = nil
self.table:set(key, value)
end
function CachedTable:delete(key)
self:set(key, nil)
end
local PageVariableNamespace = {}
function PageVariableNamespace.readOptions(options)
if not options then
options = {}
elseif type(options) == 'string' then
options = {namespace = options}
end
options.cached = Logic.nilOr(options.cached, false)
options.separator = options.separator or '.'
return options
end
PageVariableNamespace.Namespace = Namespace
PageVariableNamespace.CachedTable = CachedTable
setmetatable(PageVariableNamespace, {
__call = function(_, options_)
local options = PageVariableNamespace.readOptions(options_)
local prefix = options.namespace and options.namespace .. options.separator or ''
local pageVars = Namespace(prefix)
return options.cached
and CachedTable(pageVars)
or pageVars
end,
})
return PageVariableNamespace