模組:UnwrapConversion
外观
local p = {}
local getArgs = require('Module:Arguments').getArgs
local validVariantMap = {}
for _, variant in ipairs({
'zh',
'zh-hans',
'zh-hant',
'zh-cn',
'zh-hk',
'zh-mo',
'zh-my',
'zh-sg',
'zh-tw',
}) do
validVariantMap[variant] = true
end
local function validateFlag(input)
local ret = {}
local split = mw.text.split(input, ';')
for _, item in ipairs(split) do
item = mw.text.trim(item)
if validVariantMap[item] then
table.insert(ret, item)
end
end
return #ret > 0 and table.concat(ret, ';') or nil
end
function p._main(args)
local text = args.text or args[1]
local convFlag = args.flag or args[2]
if convFlag then
convFlag = validateFlag(convFlag)
end
local source = {}
for cp in mw.ustring.gcodepoint(text) do
table.insert(source, mw.ustring.char(cp))
end
local result = {}
local strlen = #source
local i=1
while i <= strlen do
if source[i] == "-" and source[i + 1] == "{" then
-- 跳掉轉換標籤
if source[i + 2] == "}" and source[i + 3] == "-" then
-- 無視 -{}-(畢竟最後輸出後這個 -{}- 的位置就會變成轉換標記邊界)
i = i + 4
else
i = i + 2
local depth = 1 -- 處理可能由其他模板引入的嵌套轉換標籤
table.insert(result, "-{")
while i <= strlen do
if source[i] == "-" and source[i + 1] == "{" then
-- 嵌套開始
depth = depth + 1
table.insert(result, "-{")
i = i + 2
elseif source[i] == "}" and source[i + 1] == "-" then
-- 嵌套結束
depth = depth - 1
if depth == 0 then
i = i + 2
break
end
table.insert(result, "}-")
i = i + 2
else
table.insert(result, source[i])
i = i + 1
end
end
table.insert(result, "}-")
end
else
-- 在轉換標籤外,加上轉換標籤
local buffer = {}
while i <= strlen and not (source[i] == "-" and source[i + 1] == "{") do
table.insert(buffer, source[i])
i = i + 1
end
if #buffer > 0 then
if convFlag then
table.insert(
result,
"-{" .. convFlag .. "|" .. table.concat(buffer) .. "}-"
)
else
table.insert(
result,
"-{" .. table.concat(buffer) .. "}-"
)
end
end
end
end
return table.concat(result)
end
function p.main(frame)
local args = getArgs(frame)
return p._main(args)
end
return p