Jump to content

Module:NUMBEROFSECTIONS/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Fred Gandt (talk | contribs) at 13:38, 25 March 2016 (trying a different (more obviously risky, but the last one had issues) delimiter). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
local p = {}

-- Counting function accepting a string haystack and table of needles
local function count(haystack, needles)
	local number = 0
	-- While we have needles to look for
	for index, needle in ipairs(needles) do
		-- find them all in our haystack
		for m in string.gmatch(haystack, needle) do
			number = number + 1
		end
	end
	return number
end

-- Function accepting any number of page names and section level numbers
function p.sections(frame)
	local total = 0
	local needles = {}
	local haystack = ""
	local pages = mw.text.split(frame.args[1], '#')
	local levels = mw.text.split(frame.args['level'], '%s')
	-- Iterate through levels
	for level in mw.text.gsplit(table.concat(levels), '') do
		-- and add the level needle to needles
		needles[#needles + 1] = '\n'..string.rep('=', tonumber(level))..'[^=]'
	end
	-- For each page name in pages
	for index, page in ipairs(pages) do
		-- get the raw markup
		haystack = mw.title.new(page)
		if haystack then
			-- count the sections and add to the total
			total = total + count(haystack:getContent(), needles)
		end
	end
	--[[ then return how many sections of the required level
		 are in all the pages passed ]]
	return total
end

return p