League of Legends Wiki
Advertisement
League of Legends Wiki

Для документации этого модуля может быть создана страница Модуль:Feature/doc

-- <pre>
local lib = {}
 
function lib.mergeFrames(frame, parent)
    local args = {}
    if frame then
        for k,v in pairs(frame.args) do
            args[k] = v
        end
    end
    if parent then
        for k,v in pairs(parent.args) do
            args[k] = v
        end
    end
    return args
end
 
function lib.arguments(origArgs)
    local args = {}
    for k, v in pairs(origArgs) do
        if type(v) == 'string' then
            v = mw.text.trim(v)
        end
        if v ~= '' then
            args[k] = v
        end
    end
    return args
end
 
function lib.getSortedKeys(tab)
    local keys = {}
    for k,_ in pairs(tab) do
        keys[#keys+1] = k
    end
    table.sort(keys)
    return keys
end

-- Возвращает итератор по ключам, сортированным по алфавиту
-- https://www.lua.org/pil/19.3.html
function lib.pairsByAlphabeticalKeys(t, f)
    local a = {}
    for n in pairs(t) do table.insert(a, n) end
        table.sort(a, f)
        local i = 0      -- iterator variable
        local iter = function ()   -- iterator function
            i = i + 1
            if a[i] == nil then return nil
            else return a[i], t[a[i]]
        end
    end
    return iter
end

-- Принимает на вход таблицу и фильтрует её элеметы, удовлетворяющие предикату
-- tbl - Таблица
-- preidcate - Функция, возвращающая либо true, либо false
function lib.predicate(tbl, predicate)
    local result = {}
    for k, v in pairs(tbl) do
        if(predicate(v)) then
            table.insert(result, k)
        end
    end
    return result
end
 
function lib.groupedArguments(args, numeric)
    if numeric == nil then
        numeric = true
    end
    numeric = not not numeric
 
    local base = {}
    local groups = {}
 
    for k, v in pairs(args) do
        v = mw.text.trim(v) or ''
        if v ~= '' then
            if type(k) == 'string' then
                k = mw.text.trim(k) or ''
                if k ~= '' then
                    local split = mw.text.split(k, ':')
                    if #split == 1 then
                        base[k] = v
                    else
                        local group = mw.text.trim(split[1]) or ''
                        local key = mw.text.trim(table.concat(split, ':', 2)) or ''
                        if key ~= '' and group ~= '' then
                            if numeric then
                                group = tonumber(group)
                                if group ~= nil then
                                    if groups[group] == nil then
                                        groups[group] = {}
                                    end
                                    groups[group][key] = v
                                else
                                    base[k] = v
                                end
                            else
                                if groups[group] == nil then
                                    groups[group] = {}
                                end
                                groups[group][key] = v
                            end
                        else
                            base[k] = v
                        end
                    end
                end
            elseif v ~= '' then
                base[k] = v
            end
        end
    end
    return base, groups
end

function lib.tbl_concat(frame)
    local args; if frame.args == nil then args = lib.arguments(frame) else args = lib.arguments(frame.args) end
        
    local pre = args["pre"] or args["prepend"]   or ""
    local app = args["app"] or args["append"]    or ""
    local sep = args["sep"] or args["separator"] or ","
    local tbl = args["tbl"] or args[1]
    local index = args["index"]
    local s   = ""
    
    if index ~= nil then
        s = s .. pre .. tbl[tonumber(index)] .. app
    else
        for i, v in pairs(tbl) do
            if i ~= 1 then
                s = s .. sep
            end
            s = s .. pre .. v .. app
        end
    end

    return s
end

function lib.tbl_debug(tbl)
    return table.tostring(tbl)
end
 
function lib.ternary(cond, T, F)
    if cond then
        return T
    else
        return F
    end
end
 
function lib.tbl(tbl)
    return table.tostring(tbl)
end

-- Исправляет двоякое написание имен чемпионов
function lib.validateName(_input)
    local champname = _input
 
    if champname == "Нуну и Виллумп"           
    or champname == "Виллумп"        then champname = "Нуну"    end
    if champname == "Квинн и Вэлор"
    or champname == "Вэлор"          then champname = "Квинн"   end
    if champname == "Сумеречный убийца"
    or champname == "Рааст"          then champname = "Каин"    end
    if champname == "Овечка"
    or champname == "Волк"           then champname = "Киндред" end
    if champname == "Твистед Фейт"   then champname = "Твистед Фэйт" end
 
    return champname
end

-- Исправляет двоякое написание названий предметов
function lib.validateItemName(_input)
    local itemName = _input
    if(mw.ustring.find(itemName, 'ё') ~= nil) then
        itemName = mw.ustring.gsub(itemName, 'ё', 'е')
    end
 
    if itemName == mw.ustring.lower("замерзший молот") then return "Замерзший Молот" end
    if itemName == mw.ustring.lower("глаз герольда") then return "Глаз герольда" end
 
    return itemName
end

function lib.round(val, decimals)
    if decimals == nil then
        decimals = 0
    end
    local mult = 10 ^ decimals
    local result = math.floor(val * mult + 0.5) / mult
    return result
end
 
-- Helper functions
function table.val_to_str(v)
    if "string" == type(v) then
        v = string.gsub(v, "\n", "\\n")
        if string.match(string.gsub(v, "[^'\"]", ""), '^"+$') then
            return "'" .. v .. "'"
        end
        return '"' .. string.gsub(v, '"', '\\"') .. '"'
    else
        return "table" == type(v) and table.tostring(v) or tostring(v)
    end
end
 
function table.key_to_str(k)
    if "string" == type(k) and string.match(k, "^[_%a][_%a%d]*$") then
        return k
    else
        return "[" .. table.val_to_str(k) .. "]"
    end
end
 
function table.tostring(tbl)
    local result, done = {}, {}
    for k, v in ipairs(tbl) do
        table.insert(result, table.val_to_str(v))
        done[k] = true
    end
    for k, v in pairs(tbl) do
        if not done[k] then
            table.insert(result, table.key_to_str(k) .. "=" .. table.val_to_str( v ))
        end
    end
    return "{" .. table.concat(result, ",") .. "}"
end

function lib.split(str, pattern)
    -- Splits string into a table
    --
    -- str: string to split
    -- pattern: pattern to use for splitting
    local out = {}
    local i = 1
    local split_start, split_end = mw.ustring.find(str, pattern, i)
    while split_start do
        out[#out + 1] = mw.ustring.sub(str, i, split_start - 1)
        i = split_end + 1
        split_start, split_end = mw.ustring.find(str, pattern, i)
    end
    out[#out + 1] = mw.ustring.sub(str, i)
    return out
end
 
return lib
-- </pre>
-- [[Category:Lua]]
Advertisement