Module:String count
Jump to navigation
Jump to search
Lua
CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules
This module counts the number of strings on a given page. It uses the most recent saved version of a page, so if used on the current page it will not work correctly in preview mode.
Usage
[edit]From wikitext
[edit]This module should be used through the {{String count}} template. See the template page for documentation.
From Lua
[edit]First, load the module.
local mStringCount = require('Module:String count')
Then you can use the _count function to count strings.
mStringCount._count(args)
- The args variable is a table containing arguments to be used by the function. Please see {{String count}} for documentation of the available parameters.
Code
-- 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