Module:CountryData

From Viki
Jump to navigation Jump to search

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

 1 local p = {}
 2 local mostUsed = mw.loadData('Module:CountryData/summary')
 3 
 4 local function getcontents(frame,country,params)
 5   return frame:expandTemplate({title="Country data "..country;args=params})
 6 end
 7 
 8 function p.getcachedtable(frame, country, params)
 9 	country = mostUsed.redirects[country] or country
10 	if params and next(params) then return p.gettable(frame, country, params) end
11 	-- Uses mw.loadData to cache data for the most-used templates
12 	if mostUsed.pages[country] then
13 		local cache = mw.loadData('Module:CountryData/cache' .. mostUsed.pages[country])
14 		if cache.data[country] then return cache.data[country] end
15 	end
16 	-- if not in cache
17 	return p.gettable(frame, country, params)
18 end
19 
20 function p.gettable(frame,country,params)
21 --Returns the parameters of a country data template as a Lua table
22   --If not a valid data template, return empty table
23   local bool, s = pcall(getcontents,frame,country,params or {})
24   if bool and (string.find(s,"^%{%{ *%{%{%{1") or string.find(s,"^%{%{safesubst: *%{%{%{1"))
25   then
26     --Replace parameter delimiters with arbitrary control characters
27     --to avoid clashes if param values contain equals/pipe signs
28     s = string.gsub(s,"|([^|=]-)=","\1\1%1\2")
29     s = string.gsub(s,"}}%s*$","\1")
30     --Loop over string and add params to table
31     local part = {}
32     for par in string.gmatch(s,"\1[^\1\2]-\2[^\1\2]-\1") do
33       local k = string.match(par,"\1%s*(.-)%s*\2")
34       local v = string.match(par,"\2%s*(.-)%s*\1")
35       if v and not (v=="" and string.find(k,"^flag alias")) then
36         part[k] = v
37       end
38     end
39     return part
40   else
41   	return {}
42   end
43 end
44 
45 function p.getalias(frame)
46 --Returns a single parameter value from a data template
47   local part = p.gettable(frame,frame.args[1])
48   if frame.args.variant
49     then return tostring(part[frame.args[2].."-"..frame.args.variant]
50                          or part[frame.args[2]] or frame.args.def)
51     else return tostring(part[frame.args[2]] or frame.args.def)
52   end
53 end
54 
55 function p.gettemplate(frame)
56 --For testing, recreates the country data from the created Lua table
57   --Get data table
58   local data = p.gettable(frame,frame.args[1])
59   --Concatenate fields into a template-like string
60   local out = "{{ {{{1}}}"
61   for k,v in pairs(data) do
62     out = out.."\n| "..k.." = "..v
63   end
64   return out.."\n}}"
65 end
66 
67 return p