Module:title/isTitle

From Linguifex
Jump to navigation Jump to search

Documentation for this module may be created at Module:title/isTitle/doc

local table_get_metamethod_module = "Module:table/getMetamethod"

local error = error
local rawequal = rawequal
local type = type

local function get_metamethod(...)
	get_metamethod = require(table_get_metamethod_module)
	return get_metamethod(...)
end

local title_eq, title_lt
local function get_title_mm()
	local success, eq, lt = get_metamethod(mw.title.getCurrentTitle(), "__eq", "__lt")
	if not success then
		error("Failed to fetch current title") -- this should never happen
	end
	title_eq, title_lt, get_title_mm = eq, lt, nil
	return eq
end

--[==[
Returns {true} if the input is a title object, or {false} if not.]==]
return function(obj)
	if not (obj and type(obj) == "table") then
		return false
	end
	local success, eq, lt = get_metamethod(obj, "__eq", "__lt")
	-- There's no foolproof method for checking for a title object, but the
	-- __eq and __lt metamethods should always be the same. Also discount titles
	-- that only have fragments (returned by mw.title.new() and
	-- mw.title.makeTitle() if the input starts with "#"), since they cannot
	-- represent a valid page, and are broken in various ways (e.g. attempting
	-- to access certain keys results in an error); see [[phab:T240678]].
	return success and eq ~= nil and lt ~= nil and
		rawequal(eq, (title_eq or get_title_mm())) and
		rawequal(lt, title_lt) and
		obj.prefixedText ~= ""
end