缺氧 Wiki

缺氧 wiki 编辑团队提示:注册账号并登录后浏览体验更佳 —— 官方免广告首页除外  •  启用小工具换源显示图片  •  通过参数设置定制化您的浏览体验

缺氧 Wiki 正在进行分叉讨论,欢迎参与!

如果你想帮助这个由玩家志愿编辑的 wiki 站点,欢迎加群 851803695 与其他编辑者一起参与建设!同时也欢迎加入缺氧 QQ 频道参与讨论~

了解更多

缺氧 Wiki
Advertisement
-- Module:I18n
-- This Module is used for making templates based in the Lua language.
-- See more details about Lua in [[Help:Lua]].
-- The Fandom Developer's Wiki hosts Global Lua Modules that can be imported and locally overridden.
-- The next line imports the I18n module from the [[w:c:dev:Global Lua Modules]].
local i18n = require('Dev:I18n')
-- See more details about this module at [[w:c:dev:Global_Lua_Modules/I18n]]

local fstr = mw.ustring.format
local getArgs = require('Dev:Arguments').getArgs
local fallbacks = require('Dev:Fallbacklist')
local _i18n = {}
local zhGroup = {
    'zh', 'zh-hans', 'zh-hant', 'zh-cn', 'zh-hk', 'zh-mo', 'zh-my', 'zh-sg',
    'zh-tw'
}

--- Copied: Argument substitution as $n where n > 0.
--  @function           _i18n.handleArgs
--  @param              {string} msg Message to substitute arguments into.
--  @param              {table} args Arguments table to substitute.
--  @return             {string} Resulting message.
--  @local
function _i18n.handleArgs(msg, args)
    for i, a in ipairs(args) do
        msg = (string.gsub(msg, '%$' .. tostring(i), tostring(a)))
    end
    return msg
end

--- Copied: Checks whether a message contains unprocessed wikitext.
--  Used to optimise message getter by not preprocessing pure text.
--  @function           _i18n.isWikitext
--  @param              {string} msg Message to check.
--  @return             {boolean} Whether the message contains wikitext.
function _i18n.isWikitext(msg)
    return type(msg) == 'string' and
               (msg:find('%-%-%-%-') or msg:find('%f[^\n%z][;:*#] ') or
                   msg:find('%f[^\n%z]==* *[^\n|]+ =*=%f[\n]') or
                   msg:find('%b<>') or msg:find('\'\'') or msg:find('%[%b[]%]') or
                   msg:find('{%b{}}'))
end

local oldLoad = i18n.loadMessages
i18n.loadMessages = function(...)
    local ds = oldLoad(...)
    local Data = getmetatable(ds)

    -- -- Add language conversion
    -- -- test by: = p.loadMessages('module:i18n/Creatures'):msg("STRINGS.CREATURES.SPECIES.BASICSINGLEHARVESTPLANT.NAME")
    -- function Data:msg(opts, ...)
    --     local frame = mw.getCurrentFrame()
    --     -- Argument normalization.
    --     if not self or not opts then
    --         error('missing arguments in Data:msg')
    --     end
    --     local key = type(opts) == 'table' and opts.key or opts
    --     local args = opts.args or {...}
    --     -- Configuration parameters.
    --     if opts.sources then
    --         self:fromSources(unpack(opts.sources))
    --     end
    --     if opts.lang then
    --         self:inLang(opts.lang)
    --     end
    --     -- Source handling.
    --     local source_n = self.tempSources or self._sources
    --     local source_i = {}
    --     for n, i in pairs(source_n) do
    --         source_i[i] = n
    --     end
    --     self.tempSources = nil
    --     -- Language handling.
    --     local lang = self.tempLang or self.defaultLang
    --     self.tempLang = nil
    --     -- Message fetching.
    --     local msg
    --     for i, messages in ipairs(self._messages) do
    --         -- Message data.
    --         local msg
    --         if lang == 'zh' then
    --             msg = {}
    --             local variantMsg = {}
    --             for _, variant in ipairs(zhGroup) do
    --                 variantMsg[variant] = (messages[variant] or {})[key]
    --             end
    --             for variant, variantStr in pairs(variantMsg) do
    --                 table.insert(msg, fstr("%s:%s;", variant, variantStr))
    --             end
    --             msg = fstr('-{%s}-', table.concat(msg, ' '))
    --         else
    --             msg = (messages[lang] or {})[key]
    --         end

    --         -- Fallback support (experimental).
    --         for _, l in ipairs((fallbacks[lang] or {})) do
    --             if msg == nil then
    --                 msg = (messages[l] or {})[key]
    --             end
    --         end
    --         -- Internal fallback to 'en'.
    --         msg = msg ~= nil and msg or messages.en[key]
    --         -- Handling argument substitution from Lua.
    --         if msg and source_i[i] and #args > 0 then
    --             msg = _i18n.handleArgs(msg, args)
    --         end
    --         if msg and source_i[i] and lang ~= 'qqx' then
    --             return frame and _i18n.isWikitext(msg)
    --                 and frame:preprocess(mw.text.trim(msg))
    --                 or  mw.text.trim(msg)
    --         end
    --     end
    --     return mw.text.nowiki('<' .. key .. '>')
    -- end

    -- test by: = p.loadMessages('module:i18n/Items'):msgRev("米虱面包")
    -- test by: = p.loadMessages('module:i18n/Creatures'):msgRev({key="好吃哈奇", args = {prefix="STRINGS.CREATURES.FAMILY_PLURAL."}})
    -- test by: = p.loadMessages('module:i18n/Creatures'):msgRev("好吃哈奇", {prefix="STRINGS.CREATURES.FAMILY_PLURAL."})
    -- test by: = p.loadMessages('module:i18n/Buildings'):msgRev("花盆", {pattern="STRINGS%.BUILDINGS%.PREFABS%.[^%.]+%.NAME"})
    function Data:msgRev(opts, ...)
        local frame = mw.getCurrentFrame()
        -- Argument normalization.
        if not self or not opts then
            error('missing arguments in Data:msg')
        end
        local key = type(opts) == 'table' and opts.key or opts
        local args = opts.args or ... or {}
        -- Configuration parameters.
        if opts.sources then self:fromSources(unpack(opts.sources)) end
        if opts.lang then self:inLang(opts.lang) end
        -- Source handling.
        local source_n = self.tempSources or self._sources
        local source_i = {}
        for n, i in pairs(source_n) do source_i[i] = n end
        self.tempSources = nil
        -- Language handling.
        local lang = self.tempLang or self.defaultLang
        self.tempLang = nil
        -- Message fetching.
        local function startswith(str)
            local pre = args.prefix
            return pre == nil or mw.ustring.sub(str, 1, #pre) == pre
        end
        local function endswith(str)
            local suf = args.suffix
            if suf == nil then return true end
            if #str < #suf then return false end
            return mw.ustring.sub(str, #str - #suf + 1) == suf
        end
        local msg
        for i, messages in ipairs(self._messages) do
            -- Message data.
            for k, v in pairs(messages[lang] or {}) do
                if v == key then
                    if args.pattern ~= nil then
                        if mw.ustring.match(k, args.pattern) ~= nil then
                            return k
                        end
                    else
                        if startswith(k) and endswith(k) then
                            return k
                        end
                    end
                end
            end
        end
        return mw.text.nowiki('<' .. key .. '>')
    end

    -- test by: = p.loadMessages('module:i18n/Items'):msgFuzzy("STRINGS\.ITEMS\.%u+\.BASICPLANTBAR\.NAME")
    function Data:msgFuzzy(opts, ...)
        local frame = mw.getCurrentFrame()
        -- Argument normalization.
        if not self or not opts then
            error('missing arguments in Data:msg')
        end
        local key = type(opts) == 'table' and opts.key or opts
        local args = opts.args or {...}
        -- Configuration parameters.
        if opts.sources then self:fromSources(unpack(opts.sources)) end
        if opts.lang then self:inLang(opts.lang) end
        -- Source handling.
        local source_n = self.tempSources or self._sources
        local source_i = {}
        for n, i in pairs(source_n) do source_i[i] = n end
        self.tempSources = nil
        -- Language handling.
        local lang = self.tempLang or self.defaultLang
        self.tempLang = nil
        -- Message fetching.
        local msg
        for i, messages in ipairs(self._messages) do
            -- Message data.
            for k, v in pairs(messages[lang] or {}) do
                local starts, ends = k:find(key)
                if starts == 1 and ends == #k then return v end
            end
        end
        return mw.text.nowiki('<' .. key .. '>')
    end

    setmetatable(ds, Data)
    return ds
end

-- test by: = p._list({"Elements"})
-- test by: = p._list({"Misc", prefix = "STRINGS.MISC.TAGS", suffix = "*"})
function i18n.list(frame) return error("Use [[Template:译名表]] instead.") end

-- test by: = p.conversiontable{"zh-tw"}
function i18n.conversiontable(frame)
    local args = getArgs(frame)
    local dplArgs = {
        titlematch = 'I18n/%',
        namespace = 'Module',
        nottitlematch = '%/doc',
        format = ",<br>%TITLE%,"
    }
    local dplResult = mw.getCurrentFrame():callParserFunction('#dpl:', dplArgs)
    local strings = mw.text.split(dplResult, '<br>', true)
    mw.logObject(strings)

    -- test

    local out = {}
    local entries = {["米虱木"] = "米蝨"}
    for k, v in pairs(entries) do
        table.insert(out, fstr("* %s => %s;", k, v))
    end
    return table.concat(out, "\n")
end

-- The last line produces the output for the template
return i18n
Advertisement