Zelda Wiki

Want to contribute to this wiki?
Sign up for an account, and get started!

Come join the Zelda Wiki community Discord server!

READ MORE

Zelda Wiki
Advertisement

A utility module for error-handling, mainly with respect to argument validation.

This module should be lazy-loaded using Module:UtilsPackage so that pages which do not have errors (most pages) do not get added to Special:WhatLinksHere/Module:UtilsError. (This does mean that UtilsPackage gets linked everywhere but it is already anyway.)

local utilsPackage = require("Module:UtilsPackage")

local _utilsError = utilsPackage.lazyLoad("Module:UtilsError")

...

_utilsError().warn("...")

local p = {}
local utilsMarkup = require("Module:UtilsMarkup/Link")
local utilsTable = require("Module:UtilsTable")

function p.warn(msg)
	local callStack = debug.traceback("", 3)
	local output = msg .. "\n\n"
	for line in string.gmatch(callStack, "\tModule:[^:]*:[^\n]*\n") do
		line = string.gsub(line, "\tModule:([^:]*):(.*)", ":::[[Module:%1]]:%2") 
		output = output .. line .. "\n"
	end
	mw.addWarning(output)
end

function p.invalid(argName, ...)
	local path = {...}
	return function (value)
		local msg = ("Value <code>%s</code> is invalid for arg <code>%s</code>"):format(value, argName)
		if #path > 0 then
			msg = msg .. " at path <code>" .. p.path(argName, path) .. "</code>"
		end
		p.warn(msg)
		return utilsMarkup.category("Pages with invalid function arguments")
	end
end

function p.path(baseTbl, ...)
	local path = baseTbl
	for _, pathComponent in pairs(...) do 
		path = path .. "[" .. utilsTable.print(pathComponent) .. "]"
	end
	return path
end

function p.logWarning(msg)
	local caller = ("[[%s]]"):format(p.getRootFrameTitle())
	local msg = ("%s: %s"):format(caller, msg)
	mw.addWarning(msg)
end

function p.logWarnings(messages)
	for _, msg in ipairs(messages) do
		p.logWarning(msg)
	end
end

function p.getRootFrameTitle()
	local frame = mw.getCurrentFrame()
	while frame:getParent() do
		frame = frame:getParent()
	end
	return frame:getTitle()
end

p.INVALID_TEMPLATE_ARGUMENTS = "Category:Pages using invalid template arguments"

function p.printErrorCategories(...)
	local result = ""
	for i,v in ipairs(arg) do
        result = ("[[%s]]"):format(tostring(v)) .. result
	end
	return result
end

return p
Advertisement