跳转到内容

Module:UT文本

来自Undertale Wiki

用于实现{{UT文本}}功能的模块。


local p = {}

local gsub = mw.ustring.gsub
local TAG = '</?[^>]+>'

local function normalize_lang(lang)
    if not lang or lang == '' then
        return 'zh'
    end
    lang = lang:lower()
    if lang == 'zh' or lang == 'zh-tw' or lang == 'ja' or lang == 'en' then
        return lang
    end
    return 'zh'
end

local function get_sep(lang)
    if lang == 'en' then
        return ' '
    end
    return ''
end

local function split_text(game_text)
    local result = {}
    for _, value in ipairs(mw.text.split(game_text, TAG)) do
        value = mw.text.trim(value)
        if value:len() > 0 then
            table.insert(result, value)
        end
    end
    return result
end

local function process_text(text, args)

    if args.squash ~= '0' then
        text = text:gsub('<br%s*/?>', get_sep(args.lang))
    else
        text = text:gsub('(<br%s*/?>)%s*(<br%s*/?>)', '\n\n')
    end

    if args.parts == '0' then
        local segments = split_text(text)
        text = table.concat(segments, get_sep(args.lang))
    end

    text = (args.pre or '') .. text .. (args.post or '')

text = text:gsub('  +', function(spaces)
    return spaces:gsub(' ', '&nbsp;')
end)

    if args.quote and args.quote ~= '' then
        text = gsub(text, '“', '‘')
        text = gsub(text, '”', '’')
        text = '“' .. text .. '”'
    end

    return text
end

function p.ut_text(frame)
    local args = frame.args

    local lang = normalize_lang(args.lang)

    local path = 'Module:UT文本/' .. lang

    local data = mw.loadData(path)

    local sheet = args.sheet
    local key = args.key

    local game_text = data[sheet] and data[sheet][key]

    if not game_text then
        return '<span style="color:red">文本不存在: ' 
            .. (sheet or '?') .. '/' .. (key or '?') 
            .. ' (' .. lang .. ')</span>'
    end

    local result = process_text(game_text, {
        lang = lang,
        squash = args.squash,
        pre = args.pre,
        post = args.post,
        quote = args.quote,
        parts = args.parts
    })

    return mw.text.trim(result)
end

return p