Jump to content

Module:NUMBEROFSECTIONS

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Fred Gandt (talk | contribs) at 15:52, 24 March 2016 (a few simple comments and preparedness for expansion). 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
	local index = 1
	local needle = needles[index]
	-- While we have needles to look for
	while needle 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 accepting a page name and section level numbers
function p.sections(frame)
	local needles = {}
	local levels = frame.args[2]
	local title = mw.title.new(frame.args[1])
	-- For every section level number
	for level in mw.text.gsplit(levels, "") do
		if level ~= " " then
			-- add the needle to our table of needles
			needles[#needles + 1] = "\n" ..
				string.rep("=", tonumber(level)) .. "[^=]"
		end
	end
	-- then return how many needles are in our haystack
	return count(title:getContent(), needles)
end

return p