Module:Sandbox/Jackmcbarn: Difference between revisions

Content deleted Content added
Jackmcbarn (talk | contribs)
simplify
Jackmcbarn (talk | contribs)
m Reverted edits by Jackmcbarn (talk) to last version by Le Deluge
Tags: Replaced Rollback
 
(6 intermediate revisions by 2 users not shown)
Line 1:
local getTarget = require('Module:Redirect').getTarget
local function translatenext(invariant)
local p = {}
local k, v = next(invariant.src, invariant.k)
 
invariant.k = k
local function translatenextpagetype(invariantnsText)
if k == nil then
return nsText == '' and 'articles' or (mw.ustring.lower(nsText) .. ' pages')
return nil
elseif type(k) ~= 'string' then
return k, v
end
local from = invariant.from[k]
if from ~= nil then
return from, v
elseif invariant.to[k] == nil then
return k, v
else
-- skip this key. tail call
return translatenext(invariant)
end
end
local function translate(src, to, from)
-- to contains English keys and translated values
-- if the value is a table, any of that table's values are valid translations
-- from contains translated keys and English values
-- optional if to doesn't rely on __index
-- src is the table being wrapped
if not from then
from = {}
for k,v in pairs(to) do
from[v] = k
end
end
 
function p.main(frame)
local mt = {}
local currentTitle = mw.title.getCurrentTitle()
function mt.__index(t, k)
local target = getTarget(currentTitle)
if type(k) == 'string' then
if k == niltarget then
local retval = src[to[k]]
local currentNsText, targetNsText = currentTitle.nsText, mw.title.new(target).nsText
if retval ~= nil or from[k] ~= nil then
if currentNsText ~= targetNsText then
return retval
return string.format('[[:Category:Cross-namespace redirects from %s]][[:Category:Cross-namespace redirects to %s]]', pagetype(currentNsText), pagetype(targetNsText))
end
end
return src[k]
end
return '[[:Category:Pages incorrectly tagged as cross-namespace redirects]]'
function mt.__newindex(t, k, v)
if type(k) ~= 'string' then
src[k] = v
return
end
local to = to[k]
local falseCognate = from[k] ~= nil
if to ~= nil then
if v == nil and not falseCognate then
src[k] = nil
end
src[to] = v
elseif not falseCognate then
src[k] = v
else
error('Attempt to write key "' .. k .. '" which has no translation and is a false cognate', 2)
end
end
function mt.__pairs(t)
return translatenext, {src = src, to = to, from = from}
end
function mt.__ipairs(t)
return ipairs(src)
end
return setmetatable({}, mt)
end
 
local p = {}
 
function p.main(frame)
local args = {
eins = '#ff0000',
zwei = '#ff7f00',
drei = '#FFFF00',
three = 'yellow'
}
local to = {
one = 'eins',
two = 'zwei',
three = 'drei'
}
local wrapper = translate(args, to)
return wrapper
end