Модуль:Votes
ТӀера куц
Этот модуль оценён как бета-версия. Он готов для широкого применения, но должен применяться с осторожностью.Категория:Модули:Бета-версии |
Модуль предназначен для подсчёта голосов в на страницах голосования.
Функции
[тоаде чура]Подсчёт количества голосов
{{#invoke:Votes|count|<имя страницы>}}
Параметры
[тоаде чура]page— имя страницы голосования (если страница не указана, то подсчёт ведется на текущей странице)level— уровень секций (по умолчанию 3)support— имя секции за (по умолчанию «Раьзабараш»)oppose— имя секции против (по умолчанию «Духьалбараш»)neutral— имя секции воздержались (по умолчанию «Юхаозабеннараш»)namespace— пространство имён страницы, если оно не указано в параметреpageformat— формат вывода в виде строки таблицы (row) или строки текста (mini) (по умолчанию «row»)template— шаблон форматирования результатов, принимающий параметры («за», «против», «воздержались»)unordered— флаг учета голосов в ненумерованных списках вместо нумерованных (по умолчанию «false»)
Замечания
[тоаде чура]Подсчитываются только строки нумерованного списка первого уровня. Строки HTML комментариев и зачеркнутые тегом <s></s> не учитываются.
---- Этот модуль подсчитывает голоса в секциях голосования
local votes = {}
function votes.count(frame)
local new_args = votes._getParameters( frame.args, { 'page', 'level', 'support', 'oppose', 'neutral', 'namespace', 'format', 'template', 'unordered' } );
local page = new_args['page'] or '';
local namespace = new_args['namespace'] or '';
local level = new_args['level'] or 3;
local fmt = new_args['format'] or 'row';
local template = new_args['template'] or '';
local unordered = new_args['unordered'] or false;
local sections = {
support = { name = new_args['support'] or 'Раьзабараш', count = 0},
oppose = { name = new_args['oppose'] or 'Духьалбараш', count = 0},
neutral = { name = new_args['neutral'] or 'Юхаозабеннараш', count = 0}
}
local pagepointer;
local pattern = "\n#[^#*:][^\n]+"; -- подсчёт нумерованных списков
if page == '' then
pagepointer=mw.title.getCurrentTitle()
assert(pagepointer,"failed to access getCurrentTitle")
else
pagepointer=mw.title.new(page, namespace)
assert(pagepointer,"failed to access mw.title.new("..tostring(page)..")")
end
if type( unordered ) == 'string' and unordered ~= 'false' and unordered ~= 'no' and unordered ~= '0' then
pattern = "\n%*[^#*:][^\n]+"; -- подсчёт ненумерованных списков
end
local text=pagepointer.getContent(pagepointer);
if text ~= nil then
text= mw.ustring.gsub( text, "<!%-%-.-%-%->", "" ); -- убираем HTML комментарии
local hpref = mw.ustring.rep("=", tonumber(level));
for k, v in pairs(sections) do
local name = mw.ustring.gsub( v.name, "([%(%)%.%%%+%-%*%?%[%^%$%]])", "%%%1" );
local t = mw.ustring.match(text, "\n" .. hpref .. "[^=]-" .. name .. "[^=]-" .. hpref .."(\n.-)\n=");
if t ~= nil then
t, v.count = mw.ustring.gsub(t, pattern, ""); -- количество голосов
end
end
end
local percent;
if sections.support.count == 0 then
percent = "0 %"
else
percent = mw.ustring.format("%.2f %%", sections.support.count * 100 / (sections.support.count + sections.oppose.count))
end
if template ~= '' then
local targs = {};
local pframe = frame:getParent();
if pframe ~= nil then
for key, value in pairs(pframe.args) do
targs[key] = value;
end
end
targs['раьзабараш'] = tostring(sections.support.count);
targs['духьалбараш'] = tostring(sections.oppose.count);
targs['юхаозабеннараш'] = tostring(sections.neutral.count);
return frame:expandTemplate{ title = template, args = targs }
end
if fmt == 'mini' then
return sections.support.count .. '/' .. sections.oppose.count .. '/' .. sections.neutral.count .. ' — ' .. percent;
else
return "\n<tr>" ..
"<td>" .. sections.support.count .. " </td>" ..
"<td>" .. sections.oppose.count .. " </td>" ..
"<td>" .. sections.neutral.count .. " </td>" ..
"<td>" .. percent .. " </td>" ..
"</tr>";
end
end
-- Таблица параметров
function votes._getParameters( frame_args, arg_list )
local new_args = {};
local index = 1;
local value;
for i,arg in ipairs( arg_list ) do
value = frame_args[arg]
if value == nil then
value = frame_args[index];
index = index + 1;
end
new_args[arg] = value;
end
return new_args;
end
return votes