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

Материал из Space Station 14 Вики
мНет описания правки
Нет описания правки
 
(не показаны 24 промежуточные версии этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local data = mw.loadData("Модуль:IanComradeBot/loc/data")
local p = {}
local p = {}


-- Глобальный кэш данных и индекса
-- Функция для получения таблицы данных
local cachedData = nil
function p.getData()
local cachedIndex = nil
    return data
end


-- Загрузка данных из JSON
-- Получение значения по ключу с поддержкой подключачей
local function loadData(filePath)
local function getValueByKey(data, key, subkey)
     if not cachedData then
     if not data[key] then
         local page = mw.title.new(filePath)
         return nil
        local content = page and page:getContent()
        cachedData = content and mw.text.jsonDecode(content) or nil
     end
     end
     return cachedData
      
end
    local value = data[key]
 
   
-- Создание индекса для быстрого поиска по ключам
    -- Если значение - строка, возвращаем её
local function buildIndex(data)
    if type(value) == "string" then
     if not cachedIndex then
        return value
        cachedIndex = {}
     end
        for categoryName, category in pairs(data) do
   
            for key, value in pairs(category) do
    -- Если значение - таблица (вложенная структура)
                cachedIndex[key] = value
    if type(value) == "table" then
             end
        if subkey and value[subkey] then
             return value[subkey]
         end
         end
     end
     end
     return cachedIndex
      
end
     return nil
 
-- Поиск текста по ключу через индекс
local function findTextByKey(index, key)
     return index[key] or nil
end
end


-- Поиск ключа по тексту (всё ещё перебор, но он используется реже)
-- Поиск текста по ключу (без учета регистра)
local function findKeyByText(data, text)
local function findTextByKey(data, key, subkey)
     for categoryName, category in pairs(data) do
    local searchKey = string.lower(key)
         for key, value in pairs(category) do
     for k, value in pairs(data) do
             if value == text then
         if string.lower(k) == searchKey then
                 return key
            local result = getValueByKey(data, k, subkey)
             if result then
                 return result
             end
             end
         end
         end
Строка 45: Строка 46:
end
end


-- Получение всех строк из категории
function p.GetString(frame)
local function getCategoryStrings(data, categoryName)
     local key = frame.args[1]
     local category = data[categoryName]
    local subkey = frame.args[2] or "_value"
     if not category then
 
         return nil
     if not key then
         return "Ошибка: Не указаны все необходимые параметры."
     end
     end


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


     return result
    if not result then
    return key
    end 
 
     return frame:preprocess("{{#invoke:Loc/Marking|main|<nowiki>".. result .. "</nowiki>}}")
end
end


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


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


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


     -- Построение индекса (если требуется)
     return frame:preprocess("<nowiki>".. result .. "</nowiki>")
    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
end


return p
return p

Текущая версия от 19:41, 6 февраля 2026

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

-- Загрузка данных
local data = mw.loadData("Модуль:IanComradeBot/loc/data")

local p = {}

-- Функция для получения таблицы данных
function p.getData()
    return data
end

-- Получение значения по ключу с поддержкой подключачей
local function getValueByKey(data, key, subkey)
    if not data[key] then
        return nil
    end
    
    local value = data[key]
    
    -- Если значение - строка, возвращаем её
    if type(value) == "string" then
        return value
    end
    
    -- Если значение - таблица (вложенная структура)
    if type(value) == "table" then
        if subkey and value[subkey] then
            return value[subkey]
        end
    end
    
    return nil
end

-- Поиск текста по ключу (без учета регистра)
local function findTextByKey(data, key, subkey)
    local searchKey = string.lower(key)
    for k, value in pairs(data) do
        if string.lower(k) == searchKey then
            local result = getValueByKey(data, k, subkey)
            if result then
                return result
            end
        end
    end
    return nil
end

function p.GetString(frame)
    local key = frame.args[1]
    local subkey = frame.args[2] or "_value"

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

    local result = findTextByKey(data, key, subkey)

    if not result then
    	return key
    end  
  
    return frame:preprocess("{{#invoke:Loc/Marking|main|<nowiki>".. result .. "</nowiki>}}")
end

function p.GetRawString(frame)
    local key = frame.args[1]
    local subkey = frame.args[2] or "_value"

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

    local result = findTextByKey(data, key, subkey)
    if not result then
    	return key
    end

    return frame:preprocess("<nowiki>".. result .. "</nowiki>")
end

return p