Jump to content

Module:ParameterCount/sandbox

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)--mw.log("here?")--mw.log(s)--mw.log(s:find('%S'))--mw.log(not s:find('%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)then--mw.log(key)--mw.log(val)ret=ret+1endendreturnretend-- Check shared arguments and get the parent argument count.localfunctionmain(frame,testFunc)localblankifiedTestFunclocalmodified_count=0ifyesno(frame.args.checkblanks)then-- Extend the test function to check for blanks as well.blankifiedTestFunc=function(key,val)ifnotisBlank(val)thenreturntestFunc(key,val)endendmodified_count=-1elseblankifiedTestFunc=testFuncendifframe.args.checkblanksthenmw.log("here?")modified_count=modified_count-1endlocalmodule_count=count(frame.args,blankifiedTestFunc)localparent_count=count(frame:getParent().args,blankifiedTestFunc)returnmodule_count+parent_count+modified_countendreturn{-- 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