Module:Cache

local trim = mw.text.trim local ugsub = mw.ustring.gsub local cache = require 'mw.ext.LuaCache' local VariablesLua = mw.ext.VariablesLua

local args_table -- cache

-- helper function local getArg = function(key) --Note: unnamed parameters will not be auto trimmed and named parameters will. local value = trim(args_table[key] or '') return (value ~= '') and value or nil end

local getCacheKey = function local lang = VariablesLua.var('__global__lang'); if not lang then lang = mw.getCurrentFrame:expandTemplate{ title = 'lang' } end return lang .. ':'.. (getArg(1) or getArg('key')) end

-- A simple wrap for LuaCache

return { -- get -- return cached value or nothing get = function(frame) args_table = frame.args local result = cache.get(getCacheKey) if result then return tostring(result) end end,

-- get & replace -- return cached value with all tokens replaced, or nothing getreplace = function(frame) args_table = frame.args local result = cache.get(getCacheKey) if not result then return end result = tostring(result) for token, replace in pairs(args_table) do			if mw.ustring.sub(token, 1, 1) == '$' then -- escape, to perform plain text replacement. see Module:String token = ugsub(token, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1") replace = ugsub(replace, "%%", "%%%%" ) result = ugsub(result, token, replace) -- Note: gsub returns 2 values, so result = gsub(str, gsub(token), gsub(replace)) won't work. end end return result end, -- set -- return 'true' or '' if $return or $4 = true set = function(frame) args_table = frame.args local result = cache.set(getCacheKey, getArg(2) or getArg('value'), tonumber(getArg(3) or getArg('exptime'))) if getArg('return') or getArg(4) then return result or '' end end,

-- set, then get and replace -- store value to cache then return the value with all tokens replaced. setreplace = function(frame) args_table = frame.args local str = getArg(2) or getArg('value') cache.set(getCacheKey, str, tonumber(getArg(3) or getArg('exptime')))

for token, replace in pairs(args_table) do			if mw.ustring.sub(token, 1, 1) == '$' then -- escape, to perform plain text replacement. see Module:String token = ugsub(token, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1") replace = ugsub(replace, "%%", "%%%%" ) str = ugsub(str, token, replace) end end return str end,

-- delete -- return 'true' or '' if $return or $2 = true delete = function(frame) args_table = frame.args local result = cache.delete(getCacheKey) if getArg('return') or getArg(2) then return result or '' end end,

}