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 18:18, 29 March 2023 (simplification). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

p = {}

--creates a frame object that cannot access any of the parent's args
--unless a table containing a list keys of not to inherit is provided
function disinherit(frame, onlyTheseKeys)
	local parent = frame
	local orphan = parent:newChild{}
	orphan.getParent = parent.getParent --returns nil
	orphan.args = {}
	if onlyTheseKeys then
		local family = {parent, frame}
		for f = 1, 2 do
			for k, v in pairs(family[f] and family[f].args or {}) do
				orphan.args[k] = orphan.args[k] or v
			end
		end
		parent.args = mw.clone(orphan.args)
		setmetatable(orphan.args, nil)
		for _, k in ipairs(onlyTheseKeys) do
			rawset(orphan.args, k, nil)
		end
	end
	return orphan, parent
end

-- This is borrowed from Module:Demo, since I need a way to reverse nowiki sanitization
function p.get(frame, arg, passArgs)
	local orphan, frame = disinherit(frame, passArgs and {arg or 1})
	local code = frame.args[arg or 1] or ''
	if code:match'nowiki' then
		code = mw.text.unstripNoWiki(code)
	end
	return orphan:preprocess(code)
end
function p.main(frame)
	local wikitext = p.get(frame)
	local secondParam = frame.args[2] or '' 
    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

        -- Locate template parameter syntax
        local processed = wikitext:gsub("{{{([^{}<>|]+)(|?([^{}<>|]*))}}}", function(a, b, c) return replaceTripleBraces(a, b, c, i) end)
        result = result .. processed
    end
    
    return result
end

return p