Открыть меню
Переключить меню настроек
Открыть персональное меню
Вы не представились системе
Ваш IP-адрес будет виден всем, если вы внесёте какие-либо изменения.

«Модуль:Navbox» и «Модуль:Transclude»: разница между страницами

Материал из Исламоведение
(Различия между страницами)
imported>Adminm
м 1 версия импортирована
 
imported>DimaABot
м Защищена Модуль:Transclude: Робот: Защита списка файлов. ([Редактирование=только администраторы] (бессрочно) [Переименование=только администра…
 
Строка 1: Строка 1:
--
local M={}
-- Реализует {{Навигационная таблица}} и {{Подгруппы навигационной таблицы}}.
---------------------------------------------------------
-- Основной объём кода заимствован из английского Module:Navbox.
-- Функции для работы с параметрами вызвавшего шаблона --
--
---------------------------------------------------------
 
function M.uni(f)-- Унификация имён параметров; псевдонимы.
local p = {}
    local tf, cs=f:getParent(), {};
 
    local findcs=function(a) cs[a]=f.args[a] end;
local getArgs -- lazily initialized
    (f.args['|фиксрег'] or f.args['|fixreg'] or ''):gmatch(' *([^%n]+) *', findcs);
 
    -- {{!}}фиксрег = список разделённых новыми строками аргументов, регистр которых не менять
local args
    local args,am={};
local border
    for a,v in pairs(tf.args) do
local listnums = {}
        am = a:lower():gsub('[_ ]+',' ');
local ODD_EVEN_MARKER = '\127_ODDEVEN_\127'
        args[ cs[a] and or ( f.args[am] or am ) ] = v
local RESTART_MARKER = '\127_ODDEVEN0_\127'
    end
local REGEX_MARKER = '\127_ODDEVEN(%d?)_\127'
    return tf:expandTemplate{title=f.args[1]; args=args}
 
local maintitle
local name
local navbar
local above
local image
local below
 
local titlestyle
local groupstyle
local bodystyle
local basestyle
local liststyle
local oddstyle
local evenstyle
local evenoddARG
local abovestyle
local belowstyle
local imageleft
local imageleftstyle
local style
 
local groupwidth
local listpadding
 
local bodyclass
local titleclass
local aboveclass
local belowclass
local groupclass
local listclass
local imageclass
 
local function striped(wikitext)
-- Return wikitext with markers replaced for odd/even striping.
-- Child (subgroup) navboxes are flagged with a category that is removed
-- by parent navboxes. The result is that the category shows all pages
-- where a child navbox is not contained in a parent navbox.
local orphanCat = '[[Категория:Навигационные шаблоны без родителя]]'
if border == 'subgroup' and args.orphan ~= 'yes' then
-- No change; striping occurs in outermost navbox.
return wikitext .. orphanCat
end
local first, second = 'odd', 'even'
if args.evenodd then
if args.evenodd == 'swap' then
first, second = second, first
else
first = args.evenodd
second = first
end
end
local changer
if first == second then
changer = first
else
local index = 0
changer = function (code)
if code == '0' then
-- Current occurrence is for a group before a nested table.
-- Set it to first as a valid although pointless class.
-- The next occurrence will be the first row after a title
-- in a subgroup and will also be first.
index = 0
return first
end
index = index + 1
return index % 2 == 1 and first or second
end
end
local regex = orphanCat:gsub('([%[%]])', '%%%1')
return (wikitext:gsub(regex, ''):gsub(REGEX_MARKER, changer))  -- () omits gsub count
end
 
local function addNewline(s)
if s:match('^[*:;#]') or s:match('^{|') then
return '\n' .. s ..'\n'
else
return s
end
end
 
local function renderNavBar(titleCell)
 
if navbar ~= 'off' and navbar ~= 'plain' and not (not name and mw.getCurrentFrame():getParent():getTitle():gsub('/песочница$', '') == 'Шаблон:Навигационная таблица') then
-- Check color contrast of the gear icon
local styleratio = require('Module:Color contrast')._styleratio
local gearColor = ''
local contrastStyle = titlestyle or basestyle
local gearStyleBlack = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#666;' or '')
local gearStyleWhite = (contrastStyle and mw.text.unstripNoWiki(contrastStyle) .. '; color:#fff;' or '')
if styleratio{gearStyleBlack} < styleratio{gearStyleWhite} then
gearColor = ' white'
end
--- Gear creation
titleCell
:tag('span')
:css('float', 'left')
:css('text-align', 'left')
:css('width', '5em')
:css('margin-right', '0.5em')
:wikitext('[[Файл:Wikipedia interwiki section gear icon' .. gearColor .. '.svg|14px|Просмотр этого шаблона|link=Шаблон:' .. name .. '|alt=⛭]]')
end
 
end
 
--
--   Title row
--
local function renderTitleRow(tbl)
if not maintitle then return end
 
local titleRow = tbl:tag('tr')
 
if args.titlegroup then
titleRow
:tag('th')
:attr('scope', 'row')
:addClass('navbox-group')
:addClass(args.titlegroupclass)
:cssText(basestyle)
:cssText(groupstyle)
:cssText(args.titlegroupstyle)
:wikitext(args.titlegroup)
end
 
local titleCell = titleRow:tag('th'):attr('scope', 'col')
 
if args.titlegroup then
titleCell
:css('border-left', '2px solid #fdfdfd')
:css('width', '100%')
end
 
local titleColspan = 2
if imageleft then titleColspan = titleColspan + 1 end
if image then titleColspan = titleColspan + 1 end
if args.titlegroup then titleColspan = titleColspan - 1 end
 
titleCell
:cssText(basestyle)
:cssText(titlestyle)
:addClass('navbox-title')
:attr('colspan', titleColspan)
 
renderNavBar(titleCell)
 
titleCell
:tag('div')
:attr('id', mw.uri.anchorEncode(maintitle))
:addClass(titleclass)
:css('font-size', '114%')
:css('margin', '0 5em')
:wikitext(addNewline(maintitle))
end
 
--
--   Above/Below rows
--
 
local function getAboveBelowColspan()
local ret = 2
if imageleft then ret = ret + 1 end
if image then ret = ret + 1 end
return ret
end
 
local function renderAboveRow(tbl)
if not above then return end
 
tbl:tag('tr')
:tag('td')
:addClass('navbox-abovebelow')
:addClass(aboveclass)
:cssText(basestyle)
:cssText(abovestyle)
:attr('colspan', getAboveBelowColspan())
:tag('div')
:wikitext(addNewline(above))
end
 
local function renderBelowRow(tbl)
if not below then return end
 
tbl:tag('tr')
:tag('td')
:addClass('navbox-abovebelow')
:addClass(belowclass)
:cssText(basestyle)
:cssText(belowstyle)
:attr('colspan', getAboveBelowColspan())
:tag('div')
:wikitext(addNewline(below))
end
 
--
--   List rows
--
 
local function haveSubgroups()
for i = 1, 23 do
if (args['group' .. i] or args['заголовок' .. i] or args['группа' .. i]) and (args['list' .. i] or args['список' .. i]) then
return true
end
end
return false
end
 
local function renderListRow(tbl, index, listnum)
local row = tbl:tag('tr')
 
if index == 1 and imageleft then
row
:tag('td')
:addClass('navbox-image')
:addClass(imageclass)
:css('width', '1px')
:css('padding', '0px 7px 0px 0px')
:cssText(imageleftstyle)
:attr('rowspan', #listnums)
:tag('div')
:wikitext(addNewline(imageleft))
end
 
if (args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum]) then
local groupCell = row:tag('th')
 
groupCell
:attr('scope', 'row')
:addClass('navbox-group')
:addClass(groupclass)
:cssText(basestyle)
:css('width', groupwidth or '1px') -- If groupwidth not specified, minimize width
 
groupCell
:cssText(groupstyle)
:cssText(args['group' .. listnum .. 'style'] or args['стиль_группы' .. listnum] or args['стиль_заголовка' .. listnum])
:wikitext(args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum])
end
 
local listCell = row:tag('td')
 
if (args['group' .. listnum] or args['заголовок' .. listnum] or args['группа' .. listnum]) then
listCell
:css('text-align', 'left')
:css('border-left-width', '2px')
:css('border-left-style', 'solid')
else
if haveSubgroups() then
listCell
:attr('colspan', 2)
end
end
 
if not groupwidth then
listCell:css('width', '100%')
end
 
local rowstyle  -- usually nil so cssText(rowstyle) usually adds nothing
if index % 2 == 1 then
rowstyle = oddstyle
else
rowstyle = evenstyle
end
 
local listText = args['list' .. listnum] or args['список' .. listnum]
local oddEven = ODD_EVEN_MARKER
if listText:sub(1, 12) == '</div><table' then
-- Assume list text is for a subgroup navbox so no automatic striping for this row.
oddEven = listText:find('<th[^>]*"navbox%-title"') and RESTART_MARKER or 'odd'
end
listCell
:css('padding', '0px')
:cssText(liststyle)
:cssText(rowstyle)
:cssText(args['list' .. listnum .. 'style'] or args['стиль_списка' .. listnum])
:addClass('navbox-list')
:addClass('navbox-' .. oddEven)
:addClass(listclass)
:tag('div')
:css('padding', args['list' .. listnum .. 'padding'] or listpadding or '0em 0.25em')
:wikitext(addNewline(listText))
 
if index == 1 and image then
row
:tag('td')
:addClass('navbox-image')
:addClass(imageclass)
:css('width', '1px')
:css('padding', '0px 0px 0px 7px')
:cssText(imagestyle)
:attr('rowspan', #listnums)
:tag('div')
:wikitext(addNewline(image))
end
end
end


--
M['forall'] = function(f)-- Итератор по аргументам вызывающего шаблона.
--   Tracking categories
    -- f.args[1] — имя вызываемого шаблона.
--
    local tf,ac,res,tln,sep,gl=f:getParent(),{},{},f.args[1]:match('^%s*([^#]-)%s*#(.*)$'),tonumber(f.args[2]) or 1;
local function needsChangetoSubgroups()
    if not tln then tln,sep=f.args[1]:match('^%s*(.-)%s*$'),'' end
for i = 1, 23 do
    for p,k in pairs(f.args) do if type(p)=='string' then ac[p]=k end end
if (args['group' .. i] or args['заголовок' .. i] or args['группа' .. i]) and not (args['list' .. i] or args['список' .. i]) then
    local ans,i,ablk={},1;
return true
    while tf.args[i] do
end
        if gl==1 then
end
            ans[i] = tf:expandTemplate{ title=tln; args={tf.args[i], unpack(ac)} }
return false
        else
            ablk={}; for j = 0, gl-1 do ablk[j] = tf.args[i*gl+j] end;
            for k,v in pairs(ac) do ablk[k]=v end;
            ans[i] = tf:expandTemplate{ title=tln; args=ablk }
        end
        i = i+1
    end
    return table.concat(ans,sep)
end
end


local function needsHorizontalLists()
function M.escapeparams(f)-- Нормализация
if border == 'subgroup' or args.tracking == 'no' then
-- (обезопасивание) значений параметров.
return false
    local i,ac,acn=0,{},{};
end
    local function repl(s)
local listClasses = {
        return s:gsub('{{','{{Х'):gsub('}}',"{{ЪЪ}}"):gsub('{{Х','{{ХХ}}')--: --замена фигурных скобок
['plainlist'] = true, ['hlist'] = true, ['hlist hnum'] = true,
          :gsub('=','{{=}}'):gsub('|','{{!}}')
['hlist hwrap'] = true, ['hlist vcard'] = true, ['vcard hlist'] = true,
    end
['hlist vevent'] = true, ['hlist hlist-items-nowrap'] = true, ['hlist-items-nowrap'] = true,
    for k,v in pairs(f:getParent().args) do
}
        if type(k)=='number' then ac[k]=repl(v); i=i+1
return not (listClasses[listclass] or listClasses[bodyclass])
        else acn[repl(k)]=repl(v)end
    end
    if i ~= #ac-1 then --нумерованные параметры не сплошные
        for k,v in pairs(ac) do
            if k>i then acn[tostring(k)] = v; ac[k]=nil end-- удалять в pairs можно
        end
    end
    for k,v in pairs(acn) do
        table.insert(ac, table.concat(f.args[2] or "\n ", k, f.args[3] or ' = ', v, f.args[4] or '') )
    end
    return table.concat(ac,'|')
end
end


-- local function hasBackgroundColors()
function M.npc(f)-- Итератор по именованно-нумерованным параметрам.
-- return mw.ustring.match(titlestyle or '','background') or mw.ustring.match(groupstyle or '','background') or mw.ustring.match(basestyle or '','background')
    local tf, ac, ns = f:getParent(), {}, {};
-- end
    for k,v in pairs(tf.args) do
 
        local b,n = string.match(k,"^(.-)%s*(%d*)$");
local function isIllegible()
        n = tonumber(n);
local styleratio = require('Module:Color contrast')._styleratio
        if n then
 
            if f.args[b] then
for key, style in pairs(args) do
                if not ac[n] then
if tostring(key):match("style$") or tostring(key):match("^стиль") then
                    ac[n] = mw.clone(f.args)
if styleratio{mw.text.unstripNoWiki(style)} < 4.5 then
                    setmetatable( ac[n], nil ) -- metatable ломает expandTemplate
return true
                    table.insert(ns,n)
end
                end
end
                ac[n][b] = v
end
            end--if f.args[b]
return false
        end--if n
    end--for
    table.sort(ns);
    local tmod = #f.args-1
    for n,i in ipairs(ns) do
        ns[n]=tf:expandTemplate{ title=f.args[n % tmod+1]; args=ac[i] }
    end
    return table.concat(ns)
end
end


local function getTrackingCategories()
function M.call(f)-- Просто вызывает шаблон с аргументами вызывающего.
local cats = {}
    return f:getParent():expandTemplate{ title=f.args[1]; args=f:getParent().args }
if needsChangetoSubgroups() then table.insert(cats, 'Навигационные шаблоны с ошибочным использованием заголовков') end
if needsHorizontalLists() then table.insert(cats, 'Навигационные шаблоны без горизонтальных списков') end
if isIllegible() then table.insert(cats, 'Потенциально нечитаемые навигационные шаблоны') end
return cats
end
end


local function renderTrackingCategories(builder)
function M.join(f)-- Версия forall с разделителем вместо шаблона.
local title = mw.title.getCurrentTitle()
    -- f.args[1] — разделитель.
if title.namespace ~= 10 then return end -- not in template space
    local t, tf, i = {}, f:getParent(), tonumber(f.args.from) or 1
local subpage = title.subpageText
    local k,j,m = tonumber(f.args.to),i,f.args[3]
if subpage == 'doc' or subpage == 'песочница' or subpage == 'тесты' then return end
    while k and i<=k or tf.args[i] do
 
    if (
for i, cat in ipairs(getTrackingCategories()) do
    ({
builder:wikitext('[[Категория:' .. cat .. ']]')
    ['_']=function(s)return s~=''end;
end
    ['s']=function(s)return not tostring(s):match("^%s*$")end
    })[m] or function() return true end
    )(tf.args[i]) then
    t[j]=tf.args[i];
    j=j+1
    end;
    i=i+1
    end
    return mw.text.listToText(t,f.args[1],f.args[2] or f.args[1])
end
end
 
-------------------------------------------------------
--
-- Функции для работы с параметрами шаблона в invoke --
--   Main navbox tables
-------------------------------------------------------
--
--[[
local function renderMainTable()
function M.split(f)-- Разрезает строку f.args[3]
local tbl = mw.html.create('table')
-- указанным в f.args[2](?) разделителем
:addClass('nowraplinks')
    -- и передаёт куски шаблону f.args[1].
:addClass(bodyclass)
    local tf, ac, oldi, i, e =f:getParent(), {}, 1, f.args[3]:find(f.args[1],1,true)
 
    -- «f.args[1]» в строке выше — точно не ошибка? --Incnis Mrsi
if maintitle and (args.state ~= 'plain' and args.state ~= 'off') then
    while i do
tbl
        table.insert( ac,  f.args[3]:sub(oldi, i-1) ); oldi=e+1
:addClass('collapsible')
    end
:addClass(args.state or 'autocollapse')
    table.insert( ac, f.args[3]:sub(oldi, #f.args[3]-1) )
end
    return f:getParent():expandTemplate{ title=f.args[1]; args=ac }
 
tbl:css('border-spacing', 0)
if border == 'subgroup' or border == 'none' then
tbl
:addClass('navbox-subgroup')
:cssText(bodystyle)
:cssText(style)
else -- regular navbox - bodystyle and style will be applied to the wrapper table
tbl
:addClass('navbox-inner')
:css('background', 'transparent')
:css('color', 'inherit')
end
tbl:cssText(args.innerstyle)
 
renderTitleRow(tbl)
renderAboveRow(tbl)
for i, listnum in ipairs(listnums) do
renderListRow(tbl, i, listnum)
end
renderBelowRow(tbl)
 
return tbl
end
end
]]


function p._navbox(navboxArgs)
function M.cycle(f)-- Действует аналогично forall по числовой переменной,
args = navboxArgs
    -- изменяющейся (по умолчанию, от 1) до f.args[2].
 
    local tf,ac=f:getParent(),{};
for k, v in pairs(args) do
    for p,k in pairs(f.args) do
local listnum = ('' .. k):match('^list(%d+)$') or ('' .. k):match('^список(%d+)$')
        if type(p)=='number' then
if listnum then table.insert(listnums, tonumber(listnum)) end
            if p>2 then ac[p-1]=k end
end
        else ac[p]=k
        end
table.sort(listnums)
    end
 
    local s,fh = f.args[2]:match('^%s*(%-?%d+)%s*%.%.') or 1,
border = mw.text.trim(args.border or args[1] or '')
        f.args[2]:match('%.%.%s*(%S.*)%s*$') or f.args[2] or '';
if border == 'child' then
    fh=tonumber(fh) or fh:match('^%s*(.-)%s*$');
border = 'subgroup'
    local acr={};
end
    if not tonumber(s) then error('Начало цикла «'..s..'» — не число') end
    local function dc()
maintitle = args.title or args['заголовок']
            local r=tf:expandTemplate{ title=f.args[1]; args={s,unpack(ac)} }
navbar = args.navbar or args['ссылка_на_просмотр']
            s=s+1;
name = args.name or args['имя']
            if r~='' then table.insert(acr,r); return r end
above = args.above or args['вверху']
    end
image = args.image or args['изображение']
    if type(fh)=='number' then  
imagestyle = args.imagestyle or args['стиль_изображения']
        while s<fh do dc() end
imageleft = args.imageleft or args['изображение2'] or args['изображение_слева']
    elseif fh~='' then
imageleftstyle = args.imageleftstyle or args.imagestyle2 or args['стиль_изображения_слева']
        while tf:expandTemplate{ title=fh; args={s,unpack(ac)} } do dc() end
below = args.below or args['внизу']
    else
titlestyle = args.titlestyle or args['стиль_основного_заголовка'] or args['стиль_заголовка']
        while dc() do end
groupstyle = args.groupstyle or args['стиль_заголовков'] or args['стиль_групп']
    end
bodystyle = args.bodystyle or args['стиль_тела']
    return table.concat(acr)
basestyle = args.basestyle or args['стиль_базовый'] or args['стиль']
style = args.style
liststyle = args.liststyle or args['стиль_списков']
oddstyle = args.oddstyle or args['стиль_нечётных'] or args['стиль_нечетных']
evenstyle = args.evenstyle or args['стиль_чётных'] or args['стиль_четных']
abovestyle = args.abovestyle or args['стиль_вверху']
belowstyle = args.belowstyle or args['стиль_внизу']
evenoddARG = args.evenodd or args['чётные_нечётные'] or args['четные_нечетные']
groupwidth = args.groupwidth or args['ширина_групп']
listpadding = args.listpadding or args['отступ_списков']
bodyclass = args.bodyclass or args['класс_тела']
titleclass = args.titleclass or args['класс_заголовка']
aboveclass = args.aboveclass or args['класс_вверху']
belowclass = args.belowclass or args['класс_внизу']
groupclass = args.groupclass or args['класс_групп']
listclass = args.listclass or args['класс_списков']
imageclass = args.imageclass or args['класс_изображения']
-- render the main body of the navbox
local tbl = renderMainTable()
 
-- render the appropriate wrapper around the navbox, depending on the border param
local res = mw.html.create()
if border == 'none' then
local nav = res:tag('div')
:attr('role', 'navigation')
:node(tbl)
if maintitle then
nav:attr('aria-labelledby', mw.uri.anchorEncode(maintitle))
else
nav:attr('aria-label', 'Навигационный шаблон')
end
elseif border == 'subgroup' then
-- We assume that this navbox is being rendered in a list cell of a parent navbox, and is
-- therefore inside a div with padding:0em 0.25em. We start with a </div> to avoid the
-- padding being applied, and at the end add a <div> to balance out the parent's </div>
res
:wikitext('</div>') -- XXX: hack due to lack of unclosed support in mw.html.
:node(tbl)
:wikitext('<div>') -- XXX: hack due to lack of unclosed support in mw.html.
else
local nav = res:tag('div')
:attr('role', 'navigation')
:addClass('navbox')
:cssText(bodystyle)
:cssText(style)
:css('padding', '3px')
:node(tbl)
if maintitle then
nav:attr('aria-labelledby', mw.uri.anchorEncode(maintitle))
else
nav:attr('aria-label', 'Навигационный шаблон')
end
end
 
renderTrackingCategories(res)
 
return striped(tostring(res))
end
end
 
--[[Функция не пашет как можно ждать — пробелы отсекаются после передачи параметров в expandTemplate
function p.navbox(frame)
function M.pass(f)-- Передаёт шаблону параметры без подрезки.
if not getArgs then
    local ac,i={},1;
getArgs = require('Module:Arguments').getArgs
    while f.args[2*i] do ac[ tonumber(f.args[2*i]) or f.args[2*i] ] = f.args[2*i+1]; i=i+1 end;
end
    return  f:getParent():expandTemplate{ title=f.args[1]; args=ac }
args = getArgs(frame, {wrappers = {'Шаблон:Навигационная таблица', 'Шаблон:Подгруппы навигационной таблицы'}})
if frame.args.border then
-- This allows Template:Navbox_subgroup to use {{#invoke:Navbox|navbox|border=...}}.
args.border = frame.args.border
end
-- Read the arguments in the order they'll be output in, to make references number in the right order.
local _
_ = maintitle
_ = above
for i = 1, 23 do
_ = args["group" .. tostring(i)] and args["заголовок" .. tostring(i)] and args["группа" .. tostring(i)]
_ = args["list" .. tostring(i)] and args["список" .. tostring(i)]
end
_ = below
 
return p._navbox(args)
end
end
 
]]
return p
return M

Версия от 16:36, 19 июля 2015

Для документации этого модуля может быть создана страница Модуль:Transclude/doc

Ошибка скрипта: Ошибка Lua: не удаётся создать процесс: proc_open(/dev/null): Failed to open stream: Operation not permitted

local M={}
---------------------------------------------------------
-- Функции для работы с параметрами вызвавшего шаблона --
---------------------------------------------------------
function M.uni(f)-- Унификация имён параметров; псевдонимы.
    local tf, cs=f:getParent(), {};
    local findcs=function(a) cs[a]=f.args[a] end;
    (f.args['|фиксрег'] or f.args['|fixreg'] or ''):gmatch(' *([^%n]+) *', findcs);
    -- {{!}}фиксрег = список разделённых новыми строками аргументов, регистр которых не менять
    local args,am={};
    for a,v in pairs(tf.args) do
        am = a:lower():gsub('[_ ]+',' ');
        args[ cs[a] and a  or  ( f.args[am] or am ) ] = v
    end
    return tf:expandTemplate{title=f.args[1]; args=args}
end

M['forall'] = function(f)-- Итератор по аргументам вызывающего шаблона.
    -- f.args[1] — имя вызываемого шаблона.
     local tf,ac,res,tln,sep,gl=f:getParent(),{},{},f.args[1]:match('^%s*([^#]-)%s*#(.*)$'),tonumber(f.args[2]) or 1;
     if not tln then tln,sep=f.args[1]:match('^%s*(.-)%s*$'),'' end
     for p,k in pairs(f.args) do if type(p)=='string' then ac[p]=k end end
     local ans,i,ablk={},1;
     while tf.args[i] do
         if gl==1 then
             ans[i] = tf:expandTemplate{ title=tln; args={tf.args[i], unpack(ac)} }
         else
             ablk={}; for j = 0, gl-1 do ablk[j] = tf.args[i*gl+j] end;
             for k,v in pairs(ac) do ablk[k]=v end;
             ans[i] = tf:expandTemplate{ title=tln; args=ablk }
         end
         i = i+1
     end
     return table.concat(ans,sep)
end

function M.escapeparams(f)-- Нормализация
	-- (обезопасивание) значений параметров.
    local i,ac,acn=0,{},{};
    local function repl(s)
        return s:gsub('{{','{{Х'):gsub('}}',"{{ЪЪ}}"):gsub('{{Х','{{ХХ}}')--: --замена фигурных скобок
           :gsub('=','{{=}}'):gsub('|','{{!}}') 
    end
    for k,v in pairs(f:getParent().args) do
        if type(k)=='number' then ac[k]=repl(v); i=i+1
        else acn[repl(k)]=repl(v)end
    end
    if i ~= #ac-1 then --нумерованные параметры не сплошные
        for k,v in pairs(ac) do
            if k>i then acn[tostring(k)] = v; ac[k]=nil end-- удалять в pairs можно
        end
    end
    for k,v in pairs(acn) do
        table.insert(ac, table.concat(f.args[2] or "\n ", k, f.args[3] or ' = ', v, f.args[4] or '') )
    end
    return table.concat(ac,'|')
end

function M.npc(f)-- Итератор по именованно-нумерованным параметрам.
    local tf, ac, ns = f:getParent(), {}, {};
    for k,v in pairs(tf.args) do
        local b,n = string.match(k,"^(.-)%s*(%d*)$");
        n = tonumber(n);
        if n then
            if f.args[b] then
                if not ac[n] then
                    ac[n] = mw.clone(f.args)
                    setmetatable( ac[n], nil ) -- metatable ломает expandTemplate
                    table.insert(ns,n)
                end
                ac[n][b] = v
            end--if f.args[b]
        end--if n
    end--for
    table.sort(ns);
    local tmod = #f.args-1
    for n,i in ipairs(ns) do
        ns[n]=tf:expandTemplate{ title=f.args[n % tmod+1]; args=ac[i] }
    end
    return table.concat(ns)
end

function M.call(f)-- Просто вызывает шаблон с аргументами вызывающего.
    return f:getParent():expandTemplate{ title=f.args[1]; args=f:getParent().args }
end

function M.join(f)-- Версия forall с разделителем вместо шаблона.
    -- f.args[1] — разделитель.
    local t, tf, i = {}, f:getParent(), tonumber(f.args.from) or 1
    local k,j,m = tonumber(f.args.to),i,f.args[3]
    while k and i<=k or tf.args[i] do
    	if (
    		({
    			['_']=function(s)return s~=''end;
    			['s']=function(s)return not tostring(s):match("^%s*$")end
    		})[m] or function() return true end
    	)(tf.args[i]) then
    		t[j]=tf.args[i];
    		j=j+1
    	end;
    	i=i+1
    end
    return mw.text.listToText(t,f.args[1],f.args[2] or f.args[1])
end
-------------------------------------------------------
-- Функции для работы с параметрами шаблона в invoke --
-------------------------------------------------------
--[[
function M.split(f)-- Разрезает строку f.args[3]
	-- указанным в f.args[2](?) разделителем
    -- и передаёт куски шаблону f.args[1].
    local tf, ac, oldi, i, e =f:getParent(), {}, 1, f.args[3]:find(f.args[1],1,true)
    -- «f.args[1]» в строке выше — точно не ошибка? --Incnis Mrsi
    while i do
        table.insert( ac,  f.args[3]:sub(oldi, i-1) ); oldi=e+1
    end
    table.insert( ac, f.args[3]:sub(oldi, #f.args[3]-1) )
    return f:getParent():expandTemplate{ title=f.args[1]; args=ac }
end
]]

function M.cycle(f)-- Действует аналогично forall по числовой переменной,
    -- изменяющейся (по умолчанию, от 1) до f.args[2].
    local tf,ac=f:getParent(),{};
    for p,k in pairs(f.args) do
        if type(p)=='number' then
            if p>2 then ac[p-1]=k end
        else ac[p]=k
        end
    end
    local s,fh = f.args[2]:match('^%s*(%-?%d+)%s*%.%.') or 1,
        f.args[2]:match('%.%.%s*(%S.*)%s*$') or f.args[2] or '';
    fh=tonumber(fh) or fh:match('^%s*(.-)%s*$');
    local acr={};
    if not tonumber(s) then error('Начало цикла «'..s..'» — не число') end
    local function dc()
            local r=tf:expandTemplate{ title=f.args[1]; args={s,unpack(ac)} }
            s=s+1;
            if r~='' then table.insert(acr,r); return r end
    end
    if type(fh)=='number' then 
        while s<fh do dc() end
    elseif fh~='' then
        while tf:expandTemplate{ title=fh; args={s,unpack(ac)} } do dc() end
    else
        while dc() do end
    end
    return table.concat(acr)
end
--[[Функция не пашет как можно ждать — пробелы отсекаются после передачи параметров в expandTemplate
function M.pass(f)-- Передаёт шаблону параметры без подрезки.
    local ac,i={},1;
    while f.args[2*i] do ac[ tonumber(f.args[2*i]) or f.args[2*i] ] = f.args[2*i+1]; i=i+1 end;
    return  f:getParent():expandTemplate{ title=f.args[1]; args=ac }
end
]]
return M