模块:RenderStations
local p = {}
local function convBool(val, default)
if val == nil then
return default
elseif type(val) == 'boolean' then
return val
elseif mw.text.trim(val) == '' then
return default
end
return (mw.text.trim(val) == '1')
end
local function makeLongStationLink(stationLink)
local function buildLongLink(linkTarget)
local l, r, c = string.find(linkTarget, "([^ ]+) %([^%)]+%)")
if l ~= nil then
return "[[" .. linkTarget .. "|" .. c .. "]]"
else
return "[[" .. linkTarget .. "]]"
end
end
return stationLink:gsub('%[%[([^%]%|]+)%|[^%]%|]+%]%]', buildLongLink)
end
function p.renderStationLinks(frame)
local adj_result
local a = frame:getParent().args
local short = convBool(a.short, true)
local spos, epos, station_name = 1, 1, nil
local pos = 1
local sys_args = { system=true, short=true }
local text = ''
for k, v in frame:getParent():argumentPairs() do
if type(k) == 'number' then
if string.len(text) > 0 then
text = text .. '|' .. v
else
text = v
end
else
if sys_args[k] == nil then
if string.len(text) > 0 then
text = text .. '|' .. k .. '=' .. v
else
text = k .. '=' .. v
end
end
end
end
text = mw.text.trim(text)
local out_texts = {}
while spos ~= nil do
spos, epos, station_name = string.find(text, '%$%$([^%$]+)%$%$', pos)
if spos ~= nil then
adj_result = require('Module:Adjacent stations')._station({
system = a.system,
station = station_name,
line = nil,
type = nil,
}, frame)
if not short then
adj_result = makeLongStationLink(adj_result)
end
table.insert(out_texts, string.sub(text, pos, spos - 1) .. adj_result)
pos = epos + 1
else
table.insert(out_texts, string.sub(text, pos, string.len(text)))
end
end
return table.concat(out_texts)
end
function p.testCases()
local frame = mw.getCurrentFrame()
local child_frame = frame:newChild{title='RenderStations', args={system='宁波轨道交通', '1号线从$$高桥西$$\n', '到$$霞浦$$\n'}}
if p.renderStationLinks(child_frame:newChild{title='renderStationLinks', args={}}) ~= '1号线从[[高桥西站 (宁波市)|高桥西]]\n|到[[霞浦站 (宁波市)|霞浦]]' then
error('renderStationLinks test failed: short=true.')
end
child_frame = frame:newChild{title='RenderStations', args={system='宁波轨道交通', short='0', '3号线从$$金海路$$\n', '到$$骆驼桥$$\n'}}
if p.renderStationLinks(child_frame:newChild{title='renderStationLinks', args={}}) ~= '3号线从[[金海路站 (宁波市)|金海路站]]\n|到[[骆驼桥站]]' then
error('renderStationLinks test failed: short=false.')
end
end
return p