Anda dapat membuat halaman dokumentasi untuk buat pada modul Scribunto ini.
Penyunting dapat melakukan uji coba pada halaman bak pasir (buat | cermin) dan kasus uji (buat) modul ini.
Subhalaman modul ini.
Penyunting dapat melakukan uji coba pada halaman bak pasir (buat | cermin) dan kasus uji (buat) modul ini.
Subhalaman modul ini.
localTemplatePar={serial="2023-03-20", suite="TemplatePar", item=15393417, globals={DateTime=20652535, FileMedia=24765326, Multilingual=47541920, TemplUtl=52364930, URLutil=10859193}} --[=[ Template parameter utility * assert * check * count * countNotEmpty * downcase() * duplicates * match * valid * verify() * TemplatePar() * failsafe() ]=] localLocal={frame=false} localFailsafe=TemplatePar localGlobalMod=Local -- Module globals Local.messagePrefix="lua-module-TemplatePar-" Local.L10nDef={} Local.L10nDef.en={ badPattern="#invoke:TemplatePar pattern syntax error", dupOpt="#invoke:TemplatePar repeated optional parameter", dupRule="#invoke:TemplatePar conflict key/pattern", empty="Error in template * undefined value for mandatory", invalid="Error in template * invalid parameter", invalidPar="#invoke:TemplatePar invalid parameter", minmax="#invoke:TemplatePar min > max", missing="#invoke:TemplatePar missing library", multiSpell="Error in template * multiple spelling of parameter", noMSGnoCAT="#invoke:TemplatePar neither message nor category", noname="#invoke:TemplatePar missing parameter name", notFound="Error in template * missing page", tooLong="Error in template * parameter too long", tooShort="Error in template * parameter too short", unavailable="Error in template * parameter name missing", undefined="Error in template * mandatory parameter missing", unknown="Error in template * unknown parameter name", unknownRule="#invoke:TemplatePar unknown rule" } Local.patterns={ ["ASCII"]="^[ -~]*$", ["ASCII+"]="^[ -~]+$", ["ASCII+1"]="^[!-~]+$", ["n"]="^[%-]?[0-9]*$", ["n>0"]="^[0-9]*[1-9][0-9]*$", ["N+"]="^[%-]?[1-9][0-9]*$", ["N>0"]="^[1-9][0-9]*$", ["x"]="^[0-9A-Fa-f]*$", ["x+"]="^[0-9A-Fa-f]+$", ["X"]="^[0-9A-F]*$", ["X+"]="^[0-9A-F]+$", ["0,0"]="^[%-]?[0-9]*,?[0-9]*$", ["0,0+"]="^[%-]?[0-9]+,[0-9]+$", ["0,0+?"]="^[%-]?[0-9]+,?[0-9]*$", ["0.0"]="^[%-]?[0-9]*[%.]?[0-9]*$", ["0.0+"]="^[%-]?[0-9]+%.[0-9]+$", ["0.0+?"]="^[%-]?[0-9]+[%.]?[0-9]*$", [".0+"]="^[%-]?[0-9]*[%.]?[0-9]+$", ["ID"]="^[A-Za-z]?[A-Za-z_0-9]*$", ["ID+"]="^[A-Za-z][A-Za-z_0-9]*$", ["ABC"]="^[A-Z]*$", ["ABC+"]="^[A-Z]+$", ["Abc"]="^[A-Z]*[a-z]*$", ["Abc+"]="^[A-Z][a-z]+$", ["abc"]="^[a-z]*$", ["abc+"]="^[a-z]+$", ["aBc+"]="^[a-z]+[A-Z][A-Za-z]*$", ["w"]="^%S*$", ["w+"]="^%S+$", ["base64"]="^[A-Za-z0-9%+/]*$", ["base64+"]="^[A-Za-z0-9%+/]+$", ["aa"]="[%a%a].*[%a%a]", ["pagename"]=string.format("^[^#<>%%[%%]|{}%c-%c%c]+$", 1,31,127), ["ref"]=string.format("%c'%c`UNIQ%s%sref%s%s%sQINU`%c'%c", 127,34,"%-","%-","%-","%x+", "%-",34,127), ["+"]="%S" } Local.boolean={["1"]=true, ["true"]=true, y=true, yes=true, on=true, ["0"]=true, ["false"]=true, ["-"]=true, n=true, no=true, off=true} Local.patternCJK=false localforeignModule=function(access,advanced,append,alt,alert) -- Fetch global module -- Precondition: -- access -- string, with name of base module -- advanced -- true, for require(); else mw.loadData() -- append -- string, with subpage part, if any; or false -- alt -- number, of wikidata item of root; or false -- alert -- true, for throwing error on data problem -- Postcondition: -- Returns whatever, probably table -- 2020-01-01 localstorage=access localfiner=function() ifappendthen storage=string.format("%s/%s", storage, append) end end localfun,lucky,r,suited ifadvancedthen fun=require else fun=mw.loadData end GlobalMod.globalModules=GlobalMod.globalModulesor{} suited=GlobalMod.globalModules[access] ifnotsuitedthen finer() lucky,r=pcall(fun,"Module:"..storage) end ifnotluckythen ifnotsuitedand type(alt)=="number"and alt>0then suited=string.format("Q%d",alt) suited=mw.wikibase.getSitelink(suited) GlobalMod.globalModules[access]=suitedortrue end iftype(suited)=="string"then storage=suited finer() lucky,r=pcall(fun,storage) end ifnotluckyandalertthen error("Missing or invalid page: "..storage) end end returnr end-- foreignModule() localfunctionForeign(access) -- Access standardized library -- Precondition: -- access -- string, with name of base module -- Postcondition: -- Return library table, or not -- Uses: localr ifLocal[access]then r=Local[access] else localbib=foreignModule(access, true, false, TemplatePar.globals[access], false) iftype(bib)=="table"and type(bib[access])=="function"then bib=bib[access]() iftype(bib)=="table"then r=bib Local[access]=bib end end end returnr end-- Foreign() localfunctioncontainsCJK(analyse) -- Is any CJK character present? -- Precondition: -- analyse -- string -- Postcondition: -- Return false iff no CJK present -- Uses: -- >< Local.patternCJK -- mw.ustring.char() -- mw.ustring.match() localr=false ifnotLocal.patternCJKthen Local.patternCJK=mw.ustring.char(91, 13312,45,40959, 131072,45,178207, 93) end ifmw.ustring.match(analyse,Local.patternCJK)then r=true end returnr end-- containsCJK() localfunctionfacility(accept,attempt) -- Check string as possible file name or other source page -- Precondition: -- accept -- string; requirement -- file -- file+ -- file: -- file:+ -- image -- image+ -- image: -- image:+ -- attempt -- string; to be tested -- Postcondition: -- Return error keyword, or false -- Uses: -- Module:FileMedia -- Foreign() -- FileMedia.isFile() -- FileMedia.isType() localr ifattemptandattempt~=""then localFileMedia=Foreign("FileMedia") ifFileMediaandtype(FileMedia.isFile)=="function" andtype(FileMedia.isType)=="function"then locals,live=accept:match("^([a-z]+)(:?)%+?$") iflivethen ifFileMedia.isType(attempt,s)then ifFileMedia.isFile(attempt)then r=false else r="notFound" end else r="invalid" end elseifFileMedia.isType(attempt,s)then r=false else r="invalid" end else r="missing" end elseifaccept:match("%+$")then r="empty" else r=false end returnr end-- facility() localfunctionfactory(say) -- Retrieve localized message string in content language -- Precondition: -- say -- string; message ID -- Postcondition: -- Return some message string -- Uses: -- > Local.messagePrefix -- > Local.L10nDef -- mw.message.new() -- mw.language.getContentLanguage() -- Module:Multilingual -- Foreign() -- TemplatePar.framing() -- Multilingual.tabData() localm=mw.message.new(Local.messagePrefix..say) localr=false ifm:isBlank()then localc=mw.language.getContentLanguage():getCode() locall10n=Local.L10nDef[c] ifl10nthen r=l10n[say] else localMultiL=Foreign("Multilingual") ifMultiLandtype(MultiL.tabData)=="function"then locallang r,lang=MultiL.tabData("I18n/Module:TemplatePar", say, false, TemplatePar.framing()) end end ifnotrthen r=Local.L10nDef.en[say] end else m:inLanguage(c) r=m:plain() end ifnotrthen r=string.format("(((%s)))",say) end returnr end-- factory() localfunctionfaculty(accept,attempt) -- Check string as possible boolean -- Precondition: -- accept -- string; requirement -- boolean -- boolean+ -- attempt -- string; to be tested -- Postcondition: -- Return error keyword, or false -- Uses: -- Module:TemplUtl -- Foreign() -- TemplUtl.faculty() localr r=mw.text.trim(attempt):lower() ifr==""then ifaccept=="boolean+"then r="empty" else r=false end elseifLocal.boolean[r]orr:match("^[01%-]+$")then r=false else localTemplUtl=Foreign("TemplUtl") ifTemplUtlandtype(TemplUtl.faculty)=="function"then r=TemplUtl.faculty(r,"-") ifr=="-"then r="invalid" else r=false end else r="invalid" end end returnr end-- faculty() localfunctionfailure(spec,suspect,options) -- Submit localized error message -- Precondition: -- spec -- string; message ID -- suspect -- string or nil; additional information -- options -- table or nil; optional details -- options.template -- Postcondition: -- Return string -- Uses: -- factory() localr=factory(spec) iftype(options)=="table"then iftype(options.template)=="string"then if#options.template>0then r=string.format("%s (%s)",r,options.template) end end end ifsuspectthen r=string.format("%s: %s",r,suspect) end returnr end-- failure() localfunctionfair(story,scan) -- Test for match (possibly user-defined with syntax error) -- Precondition: -- story -- string; parameter value -- scan -- string; pattern -- Postcondition: -- Return nil, if not matching, else non-nil -- Uses: -- mw.ustring.match() returnmw.ustring.match(story,scan) end-- fair() localfunctionfamiliar(accept,attempt) -- Check string as possible language name or list -- Precondition: -- accept -- string; requirement -- lang -- langs -- langW -- langsW -- lang+ -- langs+ -- langW+ -- langsW+ -- attempt -- string; to be tested -- Postcondition: -- Return error keyword, or false -- Uses: -- Module:Multilingual -- Foreign() -- Multilingual.isLang() localr ifattemptandattempt~=""then localMultiL=Foreign("Multilingual") ifMultiLandtype(MultiL.isLang)=="function"then locallazy=accept:find("W",1,true) ifaccept:find("s",1,true)then localgroup=mw.text.split(attempt,"%s+") r=false fori=1,#groupdo ifnotMultiL.isLang(group[i],lazy)then r="invalid" break-- for i end end-- for i elseifMultiL.isLang(attempt,lazy)then r=false else r="invalid" end else r="missing" end elseifaccept:find("+",1,true)then r="empty" else r=false end returnr end-- familiar() localfunctionfar(accept,attempt) -- Check string as possible URL -- Precondition: -- accept -- string; requirement -- url -- url+ -- attempt -- string; to be tested -- Postcondition: -- Return error keyword, or false -- Uses: -- Module:URLutil -- Foreign() -- URLutil.isWebURL() localr ifattemptandattempt~=""then localURLutil=Foreign("URLutil") ifURLutilandtype(URLutil.isWebURL)=="function"then ifURLutil.isWebURL(attempt)then r=false else r="invalid" end else r="missing" end elseifaccept:find("+",1,true)then r="empty" else r=false end returnr end-- far() localfunctionfast(accept,attempt) -- Check string as possible date or time -- Precondition: -- accept -- string; requirement -- datetime -- datetime+ -- datetime/y -- datetime/y+ -- datetime/ym -- datetime/ym+ -- datetime/ymd -- datetime/ymd+ -- attempt -- string; to be tested -- Postcondition: -- Return error keyword, or false -- Uses: -- Module:DateTime -- Foreign() -- DateTime.DateTime() localr r=mw.text.trim(attempt) ifr==""then ifaccept:find("+",1,true)then r="empty" else r=false end else localDateTime=Foreign("DateTime") iftype(DateTime)=="table"then locald=DateTime(attempt) iftype(d)=="table"then ifaccept:find("/",1,true)then r="invalid" ifaccept:sub(1,10)=="datetime/y"then ifd.yearthen r=false ifaccept:sub(1,11)=="datetime/ym"then ifd.monththen ifaccept:sub(1,12) =="datetime/ymd"then ifnotd.domthen r="invalid" end end else r="invalid" end end end end else r=false end else r="invalid" end else r="invalid" end end returnr end-- fast() localfunctionfault(store,key) -- Add key to collection string and insert separator -- Precondition: -- store -- string or nil or false; collection string -- key -- string or number; to be appended -- Postcondition: -- Return string; extended localr locals iftype(key)=="number"then s=tostring(key) else s=key end ifstorethen r=string.format("%s; %s",store,s) else r=s end returnr end-- fault() localfunctionfeasible(analyze,options,abbr) -- Check content of a value -- Precondition: -- analyze -- string to be analyzed -- options -- table or nil; optional details -- options.pattern -- options.key -- options.say -- abbr -- true: abbreviated error message -- Postcondition: -- Return string with error message as configured; -- false if valid or no answer permitted -- Uses: -- > Local.patterns -- failure() -- mw.text.trim() -- faculty() -- fast() -- facility() -- familiar() -- far() -- fair() -- containsCJK() localr=false locals=false localshow=nil localscan=false localstuff=mw.text.trim(analyze) iftype(options.pattern)=="string"then ifoptions.keythen r=failure("dupRule",false,options) else scan=options.pattern end else iftype(options.key)=="string"then s=mw.text.trim(options.key) else s="+" end ifs~="*"then scan=Local.patterns[s] end iftype(scan)=="string"then ifs=="n"ors=="0,0"ors=="0.0"then ifnotstuff:match("[0-9]")and notstuff:match("^%s*$")then scan=false ifoptions.saythen show=string.format(""%s"",options.say) end ifabbrthen r=show else r=failure("invalid",show,options) end end end elseifs~="*"then localop,n,plus=s:match("([<!=>]=?)([-0-9][%S]*)(+?)") ifopthen n=tonumber(n) ifnthen locali=tonumber(stuff) ifithen ifop=="<"then i=(i<n) elseifop=="<="then i=(i<=n) elseifop==">"then i=(i>n) elseifop==">="then i=(i>=n) elseifop=="=="then i=(i==n) elseifop=="!="then i=(i~=n) else n=false end end ifnotithen r="invalid" end elseifplusthen r="undefined" end elseifs:match("^boolean%+?$")then r=faculty(s,stuff) n=true elseifs:match("^datetime/?y?m?d?%+?$")then r=fast(s,stuff) n=true elseifs:match("^image%+?:?$")or s:match("^file%+?:?$")then r=facility(s,stuff) n=true elseifs:match("langs?W?%+?")then r=familiar(s,stuff) n=true elseifs:match("url%+?")then r=far(s,stuff) n=true end -- datetime+ -- iso8631+ -- line+ ifnotnandnotrthen r="unknownRule" end ifrthen ifoptions.saythen show=string.format(""%s" %s",options.say,s) else show=s end ifabbrthen r=show else r=failure(r,show,options) end end end end ifscanthen locallegal,got=pcall(fair,stuff,scan) iflegalthen ifnotgotthen ifs=="aa"then got=containsCJK(stuff) end ifnotgotthen ifoptions.saythen show=string.format(""%s"",options.say) end ifabbrthen r=show else r=failure("invalid",show,options) end end end else r=failure("badPattern", string.format("%s *** %s",scan,got), options) end end returnr end-- feasible() localfunctionfed(haystack,needle) -- Find needle in haystack map -- Precondition: -- haystack -- table; map of key values -- needle -- any; identifier -- Postcondition: -- Return true iff found localk,v,r fork,vinpairs(haystack)do ifk==needlethen r=true end end-- for k, v returnrorfalse end-- fed() localfunctionfetch(light,options) -- Return regular table with all parameters -- Precondition: -- light -- true: template transclusion; false: #invoke -- options -- table; optional details -- options.low -- Postcondition: -- Return table; whitespace-only values as false -- Uses: -- TemplatePar.downcase() -- TemplatePar.framing() -- frame:getParent() localg,k,v localr={} ifoptions.lowthen g=TemplatePar.downcase(options) else g=TemplatePar.framing() iflightthen g=g:getParent() end g=g.args end iftype(g)=="table"then r={} fork,vinpairs(g)do iftype(v)=="string"then ifv:match("^%s*$")then v=false end else v=false end iftype(k)=="number"then k=tostring(k) end r[k]=v end-- for k, v else r=g end returnr end-- fetch() localfunctionfigure(append,options) -- Extend options by rule from #invoke strings -- Precondition: -- append -- string or nil; requested rule -- options -- table; details -- ++ .key -- ++ .pattern -- Postcondition: -- Return sequence table localr=options iftype(append)=="string"then localstory=mw.text.trim(append) localsub=story:match("^/(.*%S)/$") iftype(sub)=="string"then sub=sub:gsub("%%!","|") :gsub("%%%(%(","{{") :gsub("%%%)%)","}}") :gsub("\\n",string.char(10)) options.pattern=sub options.key=nil else options.key=story options.pattern=nil end end returnr end-- figure() localfunctionfill(specified) -- Split requirement string separated by '=' -- Precondition: -- specified -- string or nil; requested parameter set -- Postcondition: -- Return sequence table -- Uses: -- mw.text.split() localr ifspecifiedthen locali,s r=mw.text.split(specified,"%s*=%s*") fori=#r,1,-1do s=r[i] if#s==0then table.remove(r,i) end end-- for i, -1 else r={} end returnr end-- fill() localfunctionfinalize(submit,options) -- Finalize message -- Precondition: -- submit -- string or false or nil; non-empty error message -- options -- table or nil; optional details -- options.format -- options.preview -- options.cat -- options.template -- Postcondition: -- Return string or false -- Uses: -- TemplatePar.framing() -- factory() localr=false ifsubmitthen locallazy=false locallearn=false localshow=false localopt,s iftype(options)=="table"then opt=options show=opt.format lazy=(show==""orshow=="0"orshow=="-") s=opt.preview iftype(s)=="string"and s~=""ands~="0"ands~="-"then localsniffer="{{REVISIONID}}" iflazythen show="" lazy=false end ifTemplatePar.framing():preprocess(sniffer)==""then ifs=="1"then show="*" else show=s end learn=true end end else opt={} end iflazythen ifnotopt.catthen r=string.format("%s %s", submit,factory("noMSGnoCAT")) end else r=submit end ifrandnotlazythen locali ifnotshoworshow=="*"then locale=mw.html.create("span") :attr("class","error") :wikitext("@@@") iflearnthen localmax=1000000000 localid=math.floor(os.clock()*max) localsign=string.format("error_%d",id) localbtn=mw.html.create("span") localtop=mw.html.create("div") e:attr("id",sign) btn:css({["background"]="#FFFF00", ["border"]="#FF0000 3px solid", ["font-weight"]="bold", ["padding"]="2px", ["text-decoration"]="none"}) :wikitext(">>>") sign=string.format("[[#%s|%s]]", sign,tostring(btn)) top:wikitext(sign," ",submit) mw.addWarning(tostring(top)) end show=tostring(e) end i=show:find("@@@",1,true) ifithen -- No gsub() since r might contain "%3" (e.g. URL) r=string.format("%s%s%s", show:sub(1,i-1), r, show:sub(i+3)) else r=show end end iflearnandrthen -- r = fatal( r ) end s=opt.cat iftype(s)=="string"then locallink ifopt.errNSthen localns=mw.title.getCurrentTitle().namespace localst=type(opt.errNS) ifst=="string"then localspace=string.format(".*%%s%d%%s.*",ns) localspaces=string.format(" %s ",opt.errNS) ifspaces:match(space)then link=true end elseifst=="table"then fori=1,#opt.errNSdo ifopt.errNS[i]==nsthen link=true break-- for i end end-- for i end else link=true end iflinkthen localcats,i ifnotrthen r="" end ifs:find("@@@")then iftype(opt.template)=="string"then s=s:gsub("@@@",opt.template) end end cats=mw.text.split(s,"%s*#%s*") fori=1,#catsdo s=mw.text.trim(cats[i]) if#s>0then r=string.format("%s[[Category:%s]]",r,s) end end-- for i end end end returnr end-- finalize() localfunctionfinder(haystack,needle) -- Find needle in haystack sequence -- Precondition: -- haystack -- table; sequence of key names, downcased if low -- needle -- any; key name -- Postcondition: -- Return true iff found locali fori=1,#haystackdo ifhaystack[i]==needlethen returntrue end end-- for i returnfalse end-- finder() localfunctionfix(valid,duty,got,options) -- Perform parameter analysis -- Precondition: -- valid -- table; unique sequence of known parameters -- duty -- table; sequence of mandatory parameters -- got -- table; sequence of current parameters -- options -- table or nil; optional details -- Postcondition: -- Return string as configured; empty if valid -- Uses: -- finder() -- fault() -- failure() -- fed() localr=false locallack fork,vinpairs(got)do ifk==""then lack=true break-- for k, v elseifnotfinder(valid,k)then r=fault(r,k) end end-- for k, v iflackthen r=failure("unavailable",false,options) elseifrthen r=failure("unknown", string.format(""%s"",r), options) else-- all names valid locali,s fori=1,#dutydo s=duty[i] ifnotfed(got,s)then r=fault(r,s) end end-- for i ifrthen r=failure("undefined",r,options) else-- all mandatory present fori=1,#dutydo s=duty[i] ifnotgot[s]then r=fault(r,s) end end-- for i ifrthen r=failure("empty",r,options) end end end returnr end-- fix() localfunctionflat(collection,options) -- Return all table elements with downcased string -- Precondition: -- collection -- table; k=v pairs -- options -- table or nil; optional messaging details -- Postcondition: -- Return table, may be empty; or string with error message. -- Uses: -- mw.ustring.lower() -- fault() -- failure() localk,v localr={} locale=false fork,vinpairs(collection)do iftype(k)=="string"then k=mw.ustring.lower(k) ifr[k]then e=fault(e,k) end end r[k]=v end-- for k, v ifethen r=failure("multiSpell",e,options) end returnr end-- flat() localfunctionfold(options) -- Merge two tables, create new sequence if both not empty -- Precondition: -- options -- table; details -- options.mandatory sequence to keep unchanged -- options.optional sequence to be appended -- options.low downcased expected -- Postcondition: -- Return merged table, or message string if error -- Uses: -- finder() -- fault() -- failure() -- flat() locali,e,r,s localbase=options.mandatory localextend=options.optional if#base==0then if#extend==0then r={} else r=extend end else if#extend==0then r=base else e=false fori=1,#extenddo s=extend[i] iffinder(base,s)then e=fault(e,s) end end-- for i ifethen r=failure("dupOpt",e,options) else r={} fori=1,#basedo table.insert(r,base[i]) end-- for i fori=1,#extenddo table.insert(r,extend[i]) end-- for i end end end ifoptions.lowandtype(r)=="table"then r=flat(r,options) end returnr end-- fold() localfunctionform(light,options,frame) -- Run parameter analysis on current environment -- Precondition: -- light -- true: template transclusion; false: #invoke -- options -- table or nil; optional details -- options.mandatory -- options.optional -- frame -- object; #invoke environment, or false -- Postcondition: -- Return string with error message as configured; -- false if valid -- Uses: -- TemplatePar.framing() -- fold() -- fetch() -- fix() -- finalize() localduty,r ifframethen TemplatePar.framing(frame) end iftype(options)=="table"then iftype(options.mandatory)~="table"then options.mandatory={} end duty=options.mandatory iftype(options.optional)~="table"then options.optional={} end r=fold(options) else options={} duty={} r={} end iftype(r)=="table"then localgot=fetch(light,options) iftype(got)=="table"then r=fix(r,duty,got,options) else r=got end end returnfinalize(r,options) end-- form() localfunctionformat(analyze,options) -- Check validity of a value -- Precondition: -- analyze -- string to be analyzed -- options -- table or nil; optional details -- options.say -- options.min -- options.max -- Postcondition: -- Return string with error message as configured; -- false if valid or no answer permitted -- Uses: -- feasible() -- failure() localr=feasible(analyze,options,false) localshow ifoptions.minandnotrthen iftype(options.min)=="number"then iftype(options.max)=="number"then ifoptions.max<options.minthen r=failure("minmax", string.format("%d > %d", options.min, options.max), options) end end if#analyze<options.minandnotrthen show=" <"..options.min ifoptions.saythen show=string.format("%s "%s"",show,options.say) end r=failure("tooShort",show,options) end else r=failure("invalidPar","min",options) end end ifoptions.maxandnotrthen iftype(options.max)=="number"then if#analyze>options.maxthen show=" >"..options.max ifoptions.saythen show=string.format("%s "%s"",show,options.say) end r=failure("tooLong",show,options) end else r=failure("invalidPar","max",options) end end returnr end-- format() localfunctionformatted(assignment,access,options) -- Check validity of one particular parameter in a collection -- Precondition: -- assignment -- collection -- access -- id of parameter in collection -- options -- table or nil; optional details -- Postcondition: -- Return string with error message as configured; -- false if valid or no answer permitted -- Uses: -- mw.text.trim() -- format() -- failure() localr=false iftype(assignment)=="table"then localstory=assignment.args[access]or"" iftype(access)=="number"then story=mw.text.trim(story) end iftype(options)~="table"then options={} end options.say=access r=format(story,options) end returnr end-- formatted() localfunctionfurnish(frame,action) -- Prepare #invoke evaluation of .assert() or .valid() -- Precondition: -- frame -- object; #invoke environment -- action -- "assert" or "valid" -- Postcondition: -- Return string with error message or "" -- Uses: -- form() -- failure() -- finalize() -- TemplatePar.valid() -- TemplatePar.assert() localoptions={mandatory={"1"}, optional={"2", "cat", "errNS", "low", "max", "min", "format", "preview", "template"}, template=string.format("#invoke:%s|%s|", "TemplatePar", action) } localr=form(false,options,frame) ifnotrthen locals options={cat=frame.args.cat, errNS=frame.args.errNS, low=frame.args.low, format=frame.args.format, preview=frame.args.preview, template=frame.args.template } options=figure(frame.args[2],options) iftype(frame.args.min)=="string"then s=frame.args.min:match("^%s*([0-9]+)%s*$") ifsthen options.min=tonumber(s) else r=failure("invalidPar", "min="..frame.args.min, options) end end iftype(frame.args.max)=="string"then s=frame.args.max:match("^%s*([1-9][0-9]*)%s*$") ifsthen options.max=tonumber(s) else r=failure("invalidPar", "max="..frame.args.max, options) end end ifrthen r=finalize(r,options) else s=frame.args[1]or"" r=tonumber(s) if(r)then s=r end ifaction=="valid"then r=TemplatePar.valid(s,options) elseifaction=="assert"then r=TemplatePar.assert(s,"",options) end end end returnror"" end-- furnish() TemplatePar.assert=function(analyze,append,options) -- Perform parameter analysis on a single string -- Precondition: -- analyze -- string to be analyzed -- append -- string: append error message, prepending <br /> -- false or nil: throw error with message -- options -- table; optional details -- Postcondition: -- Return string with error message as configured; -- false if valid -- Uses: -- format() localr=format(analyze,options) if(r)then if(type(append)=="string")then if(append~="")then r=string.format("%s<br /> %s",append,r) end else error(r,0) end end returnr end-- TemplatePar.assert() TemplatePar.check=function(options) -- Run parameter analysis on current template environment -- Precondition: -- options -- table or nil; optional details -- options.mandatory -- options.optional -- Postcondition: -- Return string with error message as configured; -- false if valid -- Uses: -- form() returnform(true,options,false) end-- TemplatePar.check() TemplatePar.count=function() -- Return number of template parameters -- Postcondition: -- Return number, starting at 0 -- Uses: -- mw.getCurrentFrame() -- frame:getParent() localk,v localr=0 localt=mw.getCurrentFrame():getParent() localo=t.args fork,vinpairs(o)do r=r+1 end-- for k, v returnr end-- TemplatePar.count() TemplatePar.countNotEmpty=function() -- Return number of template parameters with more than whitespace -- Postcondition: -- Return number, starting at 0 -- Uses: -- mw.getCurrentFrame() -- frame:getParent() localk,v localr=0 localt=mw.getCurrentFrame():getParent() localo=t.args fork,vinpairs(o)do ifnotv:match("^%s*$")then r=r+1 end end-- for k, v returnr end-- TemplatePar.countNotEmpty() TemplatePar.downcase=function(options) -- Return all template parameters with downcased name -- Precondition: -- options -- table or nil; optional messaging details -- Postcondition: -- Return table, may be empty; or string with error message. -- Uses: -- mw.getCurrentFrame() -- frame:getParent() -- flat() localt=mw.getCurrentFrame():getParent() returnflat(t.args,options) end-- TemplatePar.downcase() TemplatePar.valid=function(access,options) -- Check validity of one particular template parameter -- Precondition: -- access -- id of parameter in template transclusion -- string or number -- options -- table or nil; optional details -- Postcondition: -- Return string with error message as configured; -- false if valid or no answer permitted -- Uses: -- mw.text.trim() -- TemplatePar.downcase() -- TemplatePar.framing() -- frame:getParent() -- formatted() -- failure() -- finalize() localr=type(access) ifr=="string"then r=mw.text.trim(access) if#r==0then r=false end elseifr=="number"then r=access else r=false end ifrthen localparams iftype(options)~="table"then options={} end ifoptions.lowthen params=TemplatePar.downcase(options) else params=TemplatePar.framing():getParent() end r=formatted(params,access,options) else r=failure("noname",false,options) end returnfinalize(r,options) end-- TemplatePar.valid() TemplatePar.verify=function(options) -- Perform #invoke parameter analysis -- Precondition: -- options -- table or nil; optional details -- Postcondition: -- Return string with error message as configured; -- false if valid -- Uses: -- form() returnform(false,options,false) end-- TemplatePar.verify() TemplatePar.framing=function(frame) -- Ensure availability of frame object -- Precondition: -- frame -- object; #invoke environment, or false -- Postcondition: -- Return frame object -- Uses: -- >< Local.frame ifnotLocal.framethen iftype(frame)=="table"and type(frame.args)=="table"and type(frame.getParent)=="function"and type(frame:getParent())=="table"and type(frame:getParent().getParent)=="function"and type(frame:getParent():getParent())=="nil"then Local.frame=frame else Local.frame=mw.getCurrentFrame() end end returnLocal.frame end-- TemplatePar.framing() Failsafe.failsafe=function(atleast) -- Retrieve versioning and check for compliance -- Precondition: -- atleast -- string, with required version -- or wikidata|item|~|@ or false -- Postcondition: -- Returns string -- with queried version/item, also if problem -- false -- if appropriate -- 2020-08-17 localsince=atleast locallast=(since=="~") locallinked=(since=="@") locallink=(since=="item") localr iflastorlinkorlinkedorsince=="wikidata"then localitem=Failsafe.item since=false iftype(item)=="number"anditem>0then localsuited=string.format("Q%d",item) iflinkthen r=suited else localentity=mw.wikibase.getEntity(suited) iftype(entity)=="table"then localseek=Failsafe.serialPropertyor"P348" localvsn=entity:formatPropertyValues(seek) iftype(vsn)=="table"and type(vsn.value)=="string"and vsn.value~=""then iflastandvsn.value==Failsafe.serialthen r=false elseiflinkedthen ifmw.title.getCurrentTitle().prefixedText ==mw.wikibase.getSitelink(suited)then r=false else r=suited end else r=vsn.value end end end end end end iftype(r)=="nil"then ifnotsinceorsince<=Failsafe.serialthen r=Failsafe.serial else r=false end end returnr end-- Failsafe.failsafe() -- Provide external access localp={} functionp.assert(frame) -- Perform parameter analysis on some single string -- Precondition: -- frame -- object; #invoke environment -- Postcondition: -- Return string with error message or "" -- Uses: -- furnish() returnfurnish(frame,"assert") end-- p.assert() functionp.check(frame) -- Check validity of template parameters -- Precondition: -- frame -- object; #invoke environment -- Postcondition: -- Return string with error message or "" -- Uses: -- form() -- fill() localoptions={optional={"all", "opt", "cat", "errNS", "low", "format", "preview", "template"}, template="#invoke:TemplatePar|check|" } localr=form(false,options,frame) ifnotrthen options={mandatory=fill(frame.args.all), optional=fill(frame.args.opt), cat=frame.args.cat, errNS=frame.args.errNS, low=frame.args.low, format=frame.args.format, preview=frame.args.preview, template=frame.args.template } r=form(true,options,frame) end returnror"" end-- p.check() functionp.count(frame) -- Count number of template parameters -- Postcondition: -- Return string with digits including "0" -- Uses: -- TemplatePar.count() returntostring(TemplatePar.count()) end-- p.count() functionp.countNotEmpty(frame) -- Count number of template parameters which are not empty -- Postcondition: -- Return string with digits including "0" -- Uses: -- TemplatePar.countNotEmpty() returntostring(TemplatePar.countNotEmpty()) end-- p.countNotEmpty() functionp.match(frame) -- Combined analysis of parameters and their values -- Precondition: -- frame -- object; #invoke environment -- Postcondition: -- Return string with error message or "" -- Uses: -- TemplatePar.framing() -- mw.text.trim() -- mw.ustring.lower() -- failure() -- form() -- TemplatePar.downcase() -- figure() -- feasible() -- fault() -- finalize() localr=false localoptions={cat=frame.args.cat, errNS=frame.args.errNS, low=frame.args.low, format=frame.args.format, preview=frame.args.preview, template=frame.args.template } localk,v,s localparams={} TemplatePar.framing(frame) fork,vinpairs(frame.args)do iftype(k)=="number"then s,v=v:match("^ *([^=]+) *= *(%S.*%S*) *$") ifsthen s=mw.text.trim(s) ifs==""then s=false end end ifsthen ifoptions.lowthen s=mw.ustring.lower(s) end ifparams[s]then s=params[s] s[#s+1]=v else params[s]={v} end else r=failure("invalidPar",tostring(k),options) break-- for k, v end end end-- for k, v ifnotrthen s={} fork,vinpairs(params)do s[#s+1]=k end-- for k, v options.optional=s r=form(true,options,frame) end ifnotrthen localerrMiss,errValues,lack,rule localtargs=frame:getParent().args options.optional=nil ifoptions.lowthen targs=TemplatePar.downcase() else targs=frame:getParent().args end errMiss=false errValues=false fork,vinpairs(params)do options.say=k s=targs[k] ifsthen ifs==""then lack=true else lack=false end else s="" lack=true end forr,ruleinpairs(v)do options=figure(rule,options) r=feasible(s,options,true) ifrthen iflackthen iferrMissthen s="%s, "%s"" errMiss=string.format(s,errMiss,k) else errMiss=string.format(""%s"", k) end elseifnoterrMissthen errValues=fault(errValues,r) end break-- for r, rule end end-- for s, rule end-- for k, v r=(errMissorerrValues) ifrthen iferrMissthen r=failure("undefined",errMiss,options) else r=failure("invalid",errValues,options) end r=finalize(r,options) end end returnror"" end-- p.match() functionp.valid(frame) -- Check validity of one particular template parameter -- Precondition: -- frame -- object; #invoke environment -- Postcondition: -- Return string with error message or "" -- Uses: -- furnish() returnfurnish(frame,"valid") end-- p.valid() p.failsafe=function(frame) -- Versioning interface locals=type(frame) localsince ifs=="table"then since=frame.args[1] elseifs=="string"then since=frame end ifsincethen since=mw.text.trim(since) ifsince==""then since=false end end returnFailsafe.failsafe(since)or"" end-- p.failsafe functionp.TemplatePar() -- Retrieve function access for modules -- Postcondition: -- Return table with functions returnTemplatePar end-- p.TemplatePar() setmetatable(p,{__call=function(func,...) setmetatable(p,nil) returnFailsafe end}) returnp