Jump to content

Module:Road data/parser

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Happy5214 (talk | contribs) at 03:11, 6 January 2014 (Switching to new string module format). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

local p = {}
local format = mw.ustring.format
local gsub = mw.ustring.gsub
local trim = mw.text.trim
local upper = mw.ustring.upper

local prepattern = "%[(%w+)%|(.*)%|(.*)%|(.*)%]"
local pattern = "%%(%w+)%%"

local function parser(formatStr, args)
	local function testArgs(test, equals, ifexists, ifnot)
		if equals ~= '' then
			if args[test] == equals then return ifexists else return ifnot end
		else
			if args[test] and args[test] ~= '' then return ifexists else return ifnot end
		end
	end
	if type(formatStr) == 'table' then
		local hook = formatStr.hook
		if hook then
			local hooksModule = require "Module:Road data/parser/hooks"
			local hookFunction = hooksModule[hook] or error("Hook '" .. hook .. "' does not exist", 0)
			formatStr = hookFunction(formatStr, args)
		else
			local route = args.route
			formatStr = formatStr[route] or formatStr.default
		end
	end
	if formatStr == '' then return '' end
	local preprocessed = gsub(formatStr, prepattern, testArgs)
	local final = gsub(preprocessed, pattern, args)
	return trim(final)
end

local function formatString(args, form, part)
	local formatStringData = mw.loadData("Module:Road data/strings")
	local state = upper(args.state or args.province or '')
	local country
	if args.country then
		country = upper(args.country)
	else
		local countryModule = mw.loadData("Module:Road data/countrymask")
		country = countryModule[state] or 'UNK'
	end
	local typeArg = args.type
	local module
	local countryData = formatStringData[country] or ''
	if state and (type(countryData) == 'table') then
		module = countryData[state]
	else
		module = countryData
	end
	local moduleData = mw.loadData(module)
	local typeTable = moduleData[typeArg]
	if typeTable then
		return part and typeTable[form][part] or typeTable[form]
	else
		return ''
	end
end

function p.parser(passedArgs, form, part)
	local args = {state = passedArgs.state, type = passedArgs.type, route = passedArgs.route, 
	              denom = passedArgs.denom, county = passedArgs.county, dab = passedArgs.dab,
	              country = passedArgs.country}
	local formatStr = formatString(args, form, part)
	return (formatStr ~= '') and parser(formatStr, args) or nil
end

return p