Jump to content

Module:User:Mr. Stradivarius/sandbox5

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Mr. Stradivarius (talk | contribs) at 00:17, 25 March 2014 (create data-processing module requested at Wikipedia:Lua requests). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)
local mArguments = require('Module:Arguments')

local requiredFields = {'type', 'scale', 'region'}

local p = {}

local function err(msg)
	return string.format('<strong class="error">Error: %s</strong>', msg)
end

function p.main(frame)
	local args = mArguments.getArgs(frame)
	return p._main(args)
end

function p._main(args)
	local input = args[1]
	local field = args[2] or args.field
	local showCityData = args.citydata == 'yes'
	
	-- Validate input
	if not input then
		return err('no input code specified')
	elseif not field then
		return err('no field specified')
	end
	
	-- Parse the input string.
	local substrings = mw.text.split(input, '_')
	local data = {}
	for i, substring in ipairs(substrings) do
		local key, value = mw.ustring.match(substring, '^(.-):(.*)$')
		if key then
			data[key] = value
		end
	end
	
	-- Check for missing data
	if field == 'error' then
		local missingFields = {}
		for i, requiredField in ipairs(requiredFields) do
			if not data[requiredField] then
				table.insert(missingFields, requiredField)
			end
		end
		return 'The following fields were missing: '
			.. mw.text.listToText(missingFields)
	else
		local result = data[field] or ''
		if field == 'type' then
			local city, population = mw.ustring.match(result, '^(city)%((.-)%)$')
			if city then
				if showCityData then
					return population
				else
					return city
				end
			end
		end
		return result
	end
end

return p