Jump to content

Module:ArgRest

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Lemondoge (talk | contribs) at 22:20, 29 March 2023 (Lemondoge moved page Module:Sandbox/Lemondoge to Module:ArgRest without leaving a redirect: Module is now a bit more mature, so I'm moving it out of Sandbox.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

p = {}

function p.main(frame)
	local code = frame.args[1] or ''
	local secondParam = frame.args[2]
	
	if code:match'nowiki' then -- undo nowiki sanitization
		code = mw.text.unstripNoWiki(code)
	else return error("<nowiki> tags missing from first parameter") end
	
	if not secondParam then return error("second parameter missing") end -- Check for second parameter
	
	local wikitext = frame:preprocess(code):gsub("&lt;", "<"):gsub("&gt;", ">") -- angle brackets are still sanitized; undo it
    local start = tonumber(secondParam:match('(%d+)')) -- Extract the first number from the second parameter
    local result = ''
    
    local function replaceTripleBraces(parameter, _, default, i) -- extract corresponding arguments from the parent function. the _ is necessary because the pipe still gets caught in the second capture group
		return frame:getParent().args[parameter:gsub("%d+", tostring(i))] or default
    end
    
    for i = start, math.huge do
        -- Check if the parameter is defined
        if not frame:getParent().args[secondParam:gsub('%d+', tostring(i))] then 
        	break
        end

        local processed = wikitext:gsub("{{{([^{}<>|]+)(|?([^{}<>|]*))}}}", function(a, b, c) return replaceTripleBraces(a, b, c, i) end) -- Find stuff of the form {{{parameter}}} or {{{parameter|default}}} via pattern matching
        result = result .. processed
    end
    
    return result
end

return p