Module:NUMBEROFSECTIONS: Difference between revisions

Content deleted Content added
ignore empty page args
slight improvement for handling unexpected-and-wanted whitespace around the # delimiters; %s? --> %s* i.e. possible single whitespace char --> zero or more whitespace chars
 
(17 intermediate revisions by 6 users not shown)
Line 1:
local p = {}
 
-- Unescape functionality grabbed from https://stackoverflow.com/a/14899740/1832568
local function unescape(str)
str = string.gsub(str, '&#(%d+);', string.char)
str = string.gsub(str, '&#x(%d+);', function(n) return string.char(tonumber(n, 16)) end)
return str
end
 
-- Counting function accepting a string haystack and table of needles
local function count(haystack, needles)
local number = 0
local index = 1
local needle = needles[index]
-- While we have needles to look for
whilefor index, needle in ipairs(needles) do
-- find them all in our haystack
for m in string.gmatch(haystack, needle) do
number = number + 1
end
index = index + 1
needle = needles[index]
end
return number
end
 
-- Function acceptingtakes any number of # delimited page names and section level numbers
function p.sectionsmain(frame)
local index = 1
local total = 0
local page = ""
local pages = {}
local needles = {}
local haystack = ""''
-- Separate page names from # delimited string into table
-- Iterate through the args to find the page names and section levels
forlocal key,pages value= in pairsmw.text.split(unescape(frame.args[1]), do'%s*#%s*')
-- Separate whitespace delimited section level numbers into table
-- If the param specifies the section levels required
if local keylevels == mw.text.split(frame.args['level'], then'%s*')
-- Iterate through levels
-- for every section level number
for level in mw.text.gsplit(valuetable.concat(levels), ""'') do
-- and add the level needle to our table of needles
if level ~= " " then
needles[#needles + 1] = '\n'..string.rep("'="', tonumber(level)) .. "'[^=]"'
-- add the needle to our table of needles
needles[#needles + 1] = "\n" ..
string.rep("=", tonumber(level)) .. "[^=]"
end
end
-- Otherwise, add the page name to our table
elseif value ~= "" then
pages[#pages + 1] = value
end
end
-- For each page name in our tablepages
for index, page =in ipairs(pages[index]) do
-- create a haystack to search from the page content
while page do
haystack = mw.title.new(page):getContent()
-- get the raw markup
-- If we've requested the content of a legitimate page
haystack = mw.title.new(page)
if level ~= " "haystack then
-- count the sections and add to the total
total --[[ =pass totalthe +raw count(haystack:getContent(),markup and needles) to count
and add the return to total ]]
index = index + 1
total = total + count('\n' .. haystack, needles)
page = pages[index]
end
end
--[[ then return how many sections of the required level