Modul:String count

aus Wikipedia, der freien Enzyklopädie

Die Dokumentation für dieses Modul kann unter Modul:String count/Doku erstellt werden

-- This module counts the number of times a string appears on a given page.

local yesno = require('Module:Yesno')

local p = {}

local function escapePattern(s)
	-- Escape punctuation in a string so it can be used in a Lua pattern.
	s = s:gsub('%p', '%%%0')
	return s
end

function p._count(args)
	-- Get the page text, checking for common errors.
	if not args.page then
		error("no 'page' argument; please provide the name of the page you " ..
			"wish to count strings in", 2)
	end
	local title = mw.title.new(args.page)
	if not title then
		error(string.format(
			"'%s' is not a valid page name; check for invalid characters",
			args.page
		), 2)
	end
	local text = title:getContent()
	if not text then
		error(string.format(
			"could not get the content of page '%s'; check that it exists",
			title.prefixedText
		), 2)
	end
	
	-- Get the pattern
	local pattern = args.search
	if not pattern then
		error("no 'search' argument; please provide the string you wish to search for", 2)
	elseif yesno(args.plain) ~= false then
		pattern = escapePattern(pattern)
	end

	-- Find the count
	local temp, count = mw.ustring.gsub(text, pattern, '%0')
	return count
end

function p.count(frame)
	local args = require('Module:Arguments').getArgs(frame, {
		wrappers = 'Template:String count'
	})
	return p._count(args)
end

return p