Jump to content

Module:Pcall

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Awesome Aasim (talk | contribs) at 19:50, 10 March 2025. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

--- This module attempts to suppress the display of any error
-- @module pcall
-- @alias p
-- @release alpha

local p = {}

--- Does the call.
function doCall(modToCall, frame, template, pckg, fail, includeError)
	if template then
		local templateTitle = mw.title.new(modToCall, 10)
		local templateContent = templateTitle:getContent()
		
		local success, result = pcall(frame:preprocess(templateContent))
		if success then
			return result
		else
			if includeError then
				return result
			else
				return fail
			end
		end
	else
		local toCall = require("Module:" .. modToCall)[pckg]
		local success, result = pcall(toCall, frame)
		if success then
			return result
		else
			if includeError then
				return result
			else
				return fail
			end
		end
	end
end


--- Main function.
-- @param {table} frame Calling frame.
-- @return Wikitext output.
function main(modToCall, frame, template)
	local pckg = frame.args[1]
	local fail = frame.args["_fail"] or ''
	local includeError = frame.args["_error"]
	
	local topArg = 1
	for k,v in ipairs(frame.args) do
		if k - 1 >= 1 then
			frame.args[k - 1] = v
		end
		if k > topArg then
			topArg = k
		end
	end
	frame.args[topArg] = nil
	
	-- get rid of first underscore for arguments "__fail" and "__includeerror"
	for k,v in pairs(frame.args) do
		if type(k) ~= type(1) then
			if k:find("__fail") or k:find("__error") then
				frame.args[k:sub(-k:len() + 1)] = v
				frame.args[k] = nil
			end
		end
	end
	
	return doCall(modToCall, frame, template, pckg, fail, includeError)
end

setmetatable(p, {
	__index = function(t, index)
		if index:gsub()[1] == ":" then
			local newIndex = index:sub(-index:len() + 1)
			return function(frame)
				return main(newIndex, frame, true)
			end
		end
		return function(frame)
			return main(index, frame, false)
		end
	end
})

return p