Module:PersistentVariables

--! PersistentVariables --| Allows for Lua variables to persist between module invocations, and to be used --by "The JoTS" local VERSION_STR = "0.9.0.0"

--

-- [=[ Configuration ]=] -- local VAR_PREFIX

-- [=[ Interfaces ]=] -- local callerf, fprocess

-- [=[ Flags ]=] -- local installed

-- [=[ Helper functions ]=] -- local function process(str, repl) return fprocess(repl       and str:gsub("$(%w+)", repl)        or  str) end

local function retrieve(var) local raw = process("") local vtype, val = raw:match("^(%d)>(.*)") if vtype then vtype = tonumber(vtype) if vtype == 0 then val = false elseif vtype == 1 then val = true elseif vtype == 2 then val = tonumber(val) elseif vtype == 3 then -- Already formatted as string elseif vtype == 4 then -- Parse list end end return val end

local function update(vname, value) process("", {       name = VAR_PREFIX .. vname,        val = value    }) end

local function assertInstalled assert(installed,       "PersistentVariables must be installed with the :install method before using this") end

return { -- [=[ Methods ]=] -- -- These methods should only be used to setup the local installation of PersistentVariables install = function(p) -- Initialize once if installed then return else installed = true end -- Initialize interfaces callerf = mw.getCurrentFrame or error("Hell hath let loose") fprocess = callerf.preprocess -- Check dependencies: Variables extension if process("", { v = VERSION_STR }) == VERSION_STR then mw.log "Variables extension is installed on the local wiki" else error "Variables extension must be enabled on this wiki, please contact link" end -- Initializing package vars VAR_PREFIX = process "[__]_" return p   end, setVarPrefix = function(p, prefix) assertInstalled VAR_PREFIX = type(prefix) == "string" and prefix or error("Invalid variable prefix") return p   end, -- [=[ Functions ]=] -- -- Metafunctions to be used within other Lua modules bind_globals = function(gscope, globalsToBind) assertInstalled local globals = {} -- will contain actual pvars, gscope will be "wrapper" -- Bind for i,v in pairs(globalsToBind or gscope) do           globals[i] = retrieve(i) or v            gscope[i]  = nil end -- Modify indexing behavior setmetatable(gscope, {           __index = globals,            __newindex = function(_, var, val)                if globalsToBind[var] then                    globals[var] = val                    update(var, val)                else                    rawset(gscope, var, val)                end            end        }) end }