Module:User:Surjection/invoker

This is a private module sandbox of Surjection, for their own experimentation. Items in this module may be added and removed at Surjection's discretion; do not rely on this module's stability.


--[[
Replaces double-braced template "pseudo-invocations" (⦃⦃template¦1¦2¦a=3⦄⦄) by
calling module invocations according to the specified parameters.
	-- text: The text to find and replace pseudo-invocations in.
	-- templates: The supported templates for pseudo-invocations.
	   It should be a table mapping template names to functions.
	   The functions should take a single parameter, which will be
	   a table comprising the template arguments.
]]--
-- To wrap existing template entry points, try [[Module:invoker/default]].
return function (text, templates)
	local m_templateparser = require("Module:templateparser")

	local function invoke (contents)
		local template = "{{" .. mw.ustring.gsub(contents, "¦", "|") .. "}}"
		local name, args = m_templateparser.parseTemplate(template)
		if not name then
			error("Invalid pseudo-template syntax")
		end
		if not templates[name] then
			error("Unsupported pseudo-template: " .. name)
		end
		return templates[name](args)
	end

	-- handle nested templates
	while mw.ustring.find(text, "⦃⦃[^⦄]*⦃") do
		text = mw.ustring.gsub(text, "⦃⦃([^⦃]-)⦄⦄", invoke)
	end
	text = mw.ustring.gsub(text, "⦃⦃(.-)⦄⦄", invoke)
	return text
end