Module:Sandbox/Jackmcbarn: Difference between revisions
Appearance
Content deleted Content added
Jackmcbarn (talk | contribs) simplify |
Jackmcbarn (talk | contribs) test subst:! |
||
Line 1: | Line 1: | ||
local function translatenext(invariant) |
|||
local k, v = next(invariant.src, invariant.k) |
|||
invariant.k = k |
|||
if k == nil then |
|||
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 |
|||
local mt = {} |
|||
function mt.__index(t, k) |
|||
if type(k) == 'string' then |
|||
local retval = src[to[k]] |
|||
if retval ~= nil or from[k] ~= nil then |
|||
return retval |
|||
end |
|||
end |
|||
return src[k] |
|||
end |
|||
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 = {} |
local p = {} |
||
function p.main(frame) |
function p.main(frame) |
||
return frame:preprocess('{{subst:!}}') |
|||
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 |
end |
||
Revision as of 18:52, 18 November 2015
{{subst:!}}