Module:Languages/List

From NC Commons
Jump to navigation Jump to search

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

local p = {};

local nativeList = require('Module:Multilingual description/sort')
local nativeListIndex = {}
for i, lang in ipairs(nativeList) do
    nativeListIndex[lang] = i
end

--
--[[ Check this list by running this in the console of the Lua Module editor in MediaWiki:
="p.list = {'" .. table.concat(p.getSortedList(mw.language.fetchLanguageNames()), "', '") .. "'}"
]]
function p.getSortedList(mwLangList)
    local sortedList = {}
    for lang, _ in pairs(mwLangList) do
        table.insert(sortedList, lang)
    end
    pcall(function()
        table.sort(sortedList, function(lang1, lang2)
            return (nativeListIndex[lang1] or -1) <= (nativeListIndex[lang2] or -1)
        end)
    end)
    return sortedList
end

-- note that this fetch will be costly if all these languages are loaded individually with their data by Mediawiki
p.list = p.getSortedList(mw.language.fetchLanguageNames())

setmetatable(p, {
    quickTests = function()
        local i = 0
        for k, v in pairs(p.list) do
            if type(k) ~= 'number' or k < 1 or k ~= math.floor(k)
            or type(v) ~= 'string' or #v < 2 or #v > 16
            or (v):find('^[a-z][%-0-9a-z]*[0-9a-z]$') ~= 1 then
                return false, ': invalid sequence of language codes in p.list["' .. tostring(k) .. '"] = "' .. tostring(v) .. '"'
            end
            i = i + 1
        end
        if #(p.list) ~= i then return false, ': invalid sequence: length = '.. #(p.list) ' for ' .. i .. 'distinct keys' end
        return true
    end
})
--[[ To test this module in the Lua console:
=getmetatable(p).quickTests() -- must return true
--]]
return p;