Jump to content

Module:ArgRest/sandbox

From Wikipedia, the free encyclopedia
local p = {}

function p.main(frame)
	-- Undo sanitization:
	local code = frame.args[1] or ''
	if code:match'nowiki' then
		code = mw.text.unstripNoWiki(code)
	else error("<nowiki> missing from first parameter") end
	
	-- Angle brackets still remain santiized; unsanitize them
	local wikitext = code:gsub('&lt;', '<'):gsub('&gt;', '>')
	
	local secondParam = frame.args[2]
    local start = tonumber(secondParam:match('%d+')) -- Extract the first number from the second parameter
    local result = ''
    
    assert(secondParam, "second parameter missing")
    
    -- Helper for replaceTripleBraces: reads through "default" to find aliases and the actual default
    local function recurseOverBraces(str2, i)
    	local alias, _, default = str2:match("([^{}<>|]+)(|?)(.*)")
    	if _ == "" then default = nil end
    	if default and default:match("{{%b{}}}") then
    		return frame:getParent().args[alias:gsub("%d+", tostring(i))] or recurseOverBraces(default:match("{{(%b{})}}"):sub(1, -2), i)
    	else
    		return frame:getParent().args[alias:gsub("%d+", tostring(i))] or default or "{{{" .. alias .. "}}}" 
    	end
    end
    local function replaceTripleBraces(str, i) -- extract corresponding arguments from the parent function.
    	---- Since %b{} doesn't allow fine control, we must do a second search within the matched string
    	local parameter, _, default = str:match("([^{}<>|]+)(|?)(.*)")
    	
    	if _ == "" then default = nil elseif default:match("{{%b{}}}") then
    		default = recurseOverBraces(default:match("{{(%b{})}}"):sub(1, -2), i)
    	end
    	
		return frame:getParent().args[parameter:gsub("%d+", tostring(i))] or default or "{{{" .. parameter .. "}}}"
    end
    for i = start, math.huge do
        -- Check if the parameter is defined. TODO: make this check for aliases
        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)
        local processed = wikitext:gsub("%{%{(%b{})%}%}", function(a) return replaceTripleBraces(a:sub(1, -2), i) end)  --matches everything in triple braces
        result = result .. processed
    end
    
    return frame:preprocess(result)
end

return p