Jump to content

Module:ParameterCount

Permanently protected module
From Wikipedia, the free encyclopedia

-- This module produces a count of all the arguments passed to it.localyesno=require('Module:Yesno')-- Trim a stringlocalfunctiontrim(s)returns:match('^%s*(.-)%s*$')end-- Test whether a string is blanklocalfunctionisBlank(s)returnnots:find('%S')end-- Tests whether a string is a valid positional key, and if so, returns it. If-- the key is invalid, this returns nil.localfunctionisPositionalKey(s)s=trim(s)ifs:find('^[1-9][0-9]*$')thenreturntonumber(s)endend-- Return the count of all arguments for which testFunc returns a truthy value.localfunctioncount(args,testFunc)localret=0forkey,valinpairs(args)doiftestFunc(key,val)thenret=ret+1endendreturnretend-- Check shared arguments and get the parent argument count.localfunctionmain(frame,testFunc)localblankifiedTestFuncifyesno(frame.args.checkblanks)~=falsethen-- Extend the test function to check for blanks as well.blankifiedTestFunc=function(key,val)ifnotisBlank(val)thenreturntestFunc(key,val)endendelseblankifiedTestFunc=testFuncendreturncount(frame:getParent().args,blankifiedTestFunc)endreturn{-- Called with {{#invoke:ParameterCount|all}}-- All specified parameters are counted, even those not supported by the-- template.all=function(frame)returnmain(frame,function()returntrueend)end,-- Called with {{#invoke:ParameterCount|main}}-- Users can specify a list of parameters to check, and a list of Lua-- Ustring patterns to check each parameter against.main=function(frame)localargs=frame.argslocalkeys,patterns={},{}-- Get key listfori,keyinipairs(args)dolocalpositionalKey=isPositionalKey(key)ifpositionalKeythenkeys[positionalKey]=trueelsekeys[trim(key)]=trueendend-- Get patternsdolocalfunctiongetPattern(i)localpattern=args['pattern'..tostring(i)]ifpatternandpattern~=''thenreturnpatternendendlocali=1localpattern=getPattern(i)whilepatterndopatterns[i]=patterni=i+1pattern=getPattern(i)endend-- Construct the test functionlocaltestFunc=function(key,val)ifkeys[key]thenreturntrueendfori,patterninipairs(patterns)doifmw.ustring.find(tostring(key),pattern)thenreturntrueendendreturnfalseendreturnmain(frame,testFunc)end}
close