Модуль:Ftl: различия между версиями

Материал из Space Station 14 Вики
Нет описания правки
мНет описания правки
(не показаны 2 промежуточные версии этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


-- Загрузка данных
-- Глобальный кэш данных и индекса
local cachedData = nil
local cachedIndex = nil
 
-- Загрузка данных из JSON
local function loadData(filePath)
local function loadData(filePath)
     local page = mw.title.new(filePath)
     if not cachedData then
    local content = page and page:getContent()
        local page = mw.title.new(filePath)
    return content and mw.text.jsonDecode(content) or nil
        local content = page and page:getContent()
        cachedData = content and mw.text.jsonDecode(content) or nil
    end
    return cachedData
end
end


-- Индексация данных для быстрого поиска
-- Создание индекса для быстрого поиска по ключам
local function indexData(data)
local function buildIndex(data)
     local indexedData = { byKey = {}, byText = {} }
     if not cachedIndex then
        cachedIndex = {}
        for categoryName, category in pairs(data) do
            for key, value in pairs(category) do
                cachedIndex[key] = value
            end
        end
    end
    return cachedIndex
end
 
-- Поиск текста по ключу через индекс
local function findTextByKey(index, key)
    return index[key] or nil
end


     for _, category in pairs(data) do
-- Поиск ключа по тексту (всё ещё перебор, но он используется реже)
local function findKeyByText(data, text)
     for categoryName, category in pairs(data) do
         for key, value in pairs(category) do
         for key, value in pairs(category) do
            indexedData.byKey[key] = value
             if value == text then
             if not indexedData.byText[value] then
                 return key
                 indexedData.byText[value] = key
             end
             end
         end
         end
     end
     end
    return nil
end


     return indexedData
-- Получение всех строк из категории
end
local function getCategoryStrings(data, categoryName)
    local category = data[categoryName]
     if not category then
        return nil
    end


-- Поиск текста по ключу (с использованием индекса)
    local result = {}
local function findTextByKey(indexedData, key)
    for _, value in pairs(category) do
     return indexedData.byKey[key] or nil
        if type(value) == "string" then
end
            table.insert(result, value)
        end
     end


-- Поиск ключа по тексту (с использованием индекса)
     return result
local function findKeyByText(indexedData, text)
     return indexedData.byText[text] or nil
end
end


Строка 43: Строка 71:
     end
     end


     -- Загрузка и индексация данных из JSON
     -- Загрузка данных из JSON
     local data = loadData('User:IanComradeBot/ftl/ru-RU.json')
     local data = loadData('User:IanComradeBot/ftl/ru-RU.json')
     if not data or type(data) ~= 'table' then
     if not data or type(data) ~= 'table' then
Строка 49: Строка 77:
     end
     end


     local indexedData = indexData(data)
    -- Построение индекса (если требуется)
     local index = buildIndex(data)


     if mode == "translation" then
     if mode == "translation" then
         local result = findTextByKey(indexedData, param)
         local result = findTextByKey(index, param)
         return result or "Ошибка: Ключ не найден."
         return result or "Ошибка: Ключ не найден."
     elseif mode == "key" then
     elseif mode == "key" then
         local result = findKeyByText(indexedData, param)
         local result = findKeyByText(data, param)
         return result or "Ошибка: Текст не найден."
         return result or "Ошибка: Текст не найден."
    elseif mode == "categories" then
        local strings = getCategoryStrings(data, param)
        if not strings or #strings == 0 then
            return "Ошибка: Категория не найдена или пуста."
        end
        local output = {}
        for _, value in ipairs(strings) do
            table.insert(output, "<li>" .. mw.text.encode(value) .. "</li>")
        end
        return table.concat(output)
     else
     else
         return "Ошибка: Неизвестный режим работы."
         return "Ошибка: Неизвестный режим работы."

Версия от 08:53, 29 января 2025

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

local p = {}

-- Глобальный кэш данных и индекса
local cachedData = nil
local cachedIndex = nil

-- Загрузка данных из JSON
local function loadData(filePath)
    if not cachedData then
        local page = mw.title.new(filePath)
        local content = page and page:getContent()
        cachedData = content and mw.text.jsonDecode(content) or nil
    end
    return cachedData
end

-- Создание индекса для быстрого поиска по ключам
local function buildIndex(data)
    if not cachedIndex then
        cachedIndex = {}
        for categoryName, category in pairs(data) do
            for key, value in pairs(category) do
                cachedIndex[key] = value
            end
        end
    end
    return cachedIndex
end

-- Поиск текста по ключу через индекс
local function findTextByKey(index, key)
    return index[key] or nil
end

-- Поиск ключа по тексту (всё ещё перебор, но он используется реже)
local function findKeyByText(data, text)
    for categoryName, category in pairs(data) do
        for key, value in pairs(category) do
            if value == text then
                return key
            end
        end
    end
    return nil
end

-- Получение всех строк из категории
local function getCategoryStrings(data, categoryName)
    local category = data[categoryName]
    if not category then
        return nil
    end

    local result = {}
    for _, value in pairs(category) do
        if type(value) == "string" then
            table.insert(result, value)
        end
    end

    return result
end

-- Основная функция модуля
function p.main(frame)
    local mode = frame.args[1]
    local param = frame.args[2]

    if not mode or not param then
        return "Ошибка: Не указаны все необходимые параметры."
    end

    -- Загрузка данных из JSON
    local data = loadData('User:IanComradeBot/ftl/ru-RU.json')
    if not data or type(data) ~= 'table' then
        return 'Ошибка: Невозможно загрузить данные из JSON.'
    end

    -- Построение индекса (если требуется)
    local index = buildIndex(data)

    if mode == "translation" then
        local result = findTextByKey(index, param)
        return result or "Ошибка: Ключ не найден."
    elseif mode == "key" then
        local result = findKeyByText(data, param)
        return result or "Ошибка: Текст не найден."
    elseif mode == "categories" then
        local strings = getCategoryStrings(data, param)
        if not strings or #strings == 0 then
            return "Ошибка: Категория не найдена или пуста."
        end

        local output = {}
        for _, value in ipairs(strings) do
            table.insert(output, "<li>" .. mw.text.encode(value) .. "</li>")
        end
        return table.concat(output)
    else
        return "Ошибка: Неизвестный режим работы."
    end
end

return p