Модуль:Prototypes/Хранилище/Предмет: различия между версиями

мНет описания правки
Нет описания правки
Строка 3: Строка 3:
-- Кэш данных
-- Кэш данных
local dataCache = {}
local dataCache = {}
local dataIndexCache = {}


-- Функция processRolls для преобразования диапазона
-- Функция processRolls для преобразования диапазона
local processRolls = function(rolls)
local processRolls = function(rolls)
     local result = {}
     if not rolls then return 'Не указан параметр rolls.' end
     if rolls and rolls.range then
 
        -- Если указан range
     if rolls.range then
         local min, max = rolls.range:match("(%d+),%s*(%d+)")
         local min, max = rolls.range:match("(%d+),%s*(%d+)")
         min, max = tonumber(min), tonumber(max)
         min, max = tonumber(min), tonumber(max)
         if min and max then
         if min and max then
             result[#result + 1] = string.format('от %d до %d.', min + 1, max + 1)
             return string.format('от %d до %d.', min + 1, max + 1)
         else
         else
             result[#result + 1] = 'Некорректный формат для range.'
             return 'Некорректный формат для range.'
         end
         end
     elseif rolls and rolls.value then
     elseif rolls.value then
         -- Если указано value
         return string.format('Будет сгенерировано %d предметов.', rolls.value)
        result[#result + 1] = string.format('Будет сгенерировано %d предметов.', rolls.value)
    else
        result[#result + 1] = 'Не указан параметр rolls.'
     end
     end
     return table.concat(result)
 
     return 'Не указан параметр rolls.'
end
end
-- Локальные функции
local loadData, findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector


-- Функция для загрузки данных с кэшированием
-- Функция для загрузки данных с кэшированием
loadData = function(filePath)
local loadData = function(filePath)
     if not dataCache[filePath] then
     if not dataCache[filePath] then
         local page = mw.title.new(filePath)
         local page = mw.title.new(filePath)
         local content = page:getContent()
         local content = page:getContent()
         dataCache[filePath] = content and mw.text.jsonDecode(content) or nil
         dataCache[filePath] = content and mw.text.jsonDecode(content) or nil
        if dataCache[filePath] then
            dataIndexCache[filePath] = buildIndex(dataCache[filePath])
        end
     end
     end
     return dataCache[filePath]
     return dataCache[filePath], dataIndexCache[filePath]
end
end


-- Создание хэш-таблицы для быстрого поиска по ID
-- Создание хэш-таблицы для быстрого поиска по ID
local function buildIndex(data)
local buildIndex = function(data)
     if not data then return {} end
     if not data then return {} end
     local index = {}
     local index = {}
Строка 49: Строка 48:


-- Поиск данных по ID через хэш-таблицу
-- Поиск данных по ID через хэш-таблицу
findDataById = function(dataIndex, id)
local findDataById = function(dataIndex, id)
     return dataIndex and dataIndex[id] or nil
     return dataIndex and dataIndex[id] or nil
end
end


-- Форматирование содержимого
-- Форматирование содержимого
formatContent = function(content)
local formatContent = function(content)
     if not content.id then
     if not content.id then
         return "Ошибка: отсутствует id у элемента."
         return "Ошибка: отсутствует id у элемента."
Строка 79: Строка 78:


-- Получение содержимого через таблицу
-- Получение содержимого через таблицу
getContentsOutput = function(contents)
local getContentsOutput = function(contents)
     local result = {}
     local result = {}
     for _, content in ipairs(contents) do
     for _, content in ipairs(contents) do
Строка 88: Строка 87:


-- Обработка вложенных таблиц
-- Обработка вложенных таблиц
processNestedSelectors = function(children)
local processNestedSelectors = function(children)
     local result = {}
     local result = {}
     for _, child in ipairs(children) do
     for _, child in ipairs(children) do
Строка 103: Строка 102:


-- Обработка таблиц
-- Обработка таблиц
getTableOutput = function(tableId)
local getTableOutput = function(tableId)
     local allSelectors = loadData('User:IanComradeBot/prototypes/AllSelector.json')
     local allSelectors, dataIndex = loadData('User:IanComradeBot/prototypes/AllSelector.json')
     local tableData = findDataById(buildIndex(allSelectors), tableId)
     if not allSelectors then return 'Таблица не найдена.' end


    local tableData = findDataById(dataIndex, tableId)
     if not tableData then return 'Таблица не найдена.' end
     if not tableData then return 'Таблица не найдена.' end


Строка 119: Строка 119:


-- Формирование списка содержащихся предметов или таблиц
-- Формирование списка содержащихся предметов или таблиц
getContainedOutput = function(data, id)
local getContainedOutput = function(data, id)
     local item = findDataById(data, id)
     local item = findDataById(buildIndex(data), id)
     if not item then return '' end
     if not item then return '' end


Строка 154: Строка 154:


-- Обработка AllSelector
-- Обработка AllSelector
handleAllSelector = function(allSelector)
local handleAllSelector = function(allSelector)
     if not allSelector.children then return '' end
     if not allSelector.children then return '' end
     return processNestedSelectors(allSelector.children)
     return processNestedSelectors(allSelector.children)
Строка 160: Строка 160:


-- Обработка GroupSelector
-- Обработка GroupSelector
handleGroupSelector = function(groupSelector)
local handleGroupSelector = function(groupSelector)
     if not groupSelector.children then return '' end
     if not groupSelector.children then return '' end
     local result = {}
     local result = {}
     local wrapperStart, wrapperEnd = "", ""
     local wrapperStart, wrapperEnd = "", ""


    -- Проверка для контейнера EntityTableContainerFill
     if groupSelector.weight and groupSelector.weight ~= "default" then
     if groupSelector.weight and groupSelector.weight ~= "default" then
         wrapperStart = string.format('<div class="together" id="%s">', groupSelector.weight)
         wrapperStart = string.format('<div class="together" id="%s">', groupSelector.weight)
Строка 190: Строка 189:


-- Обработка NestedSelector
-- Обработка NestedSelector
handleNestedSelector = function(nestedSelector, wrapped)
local handleNestedSelector = function(nestedSelector, wrapped)
     if not nestedSelector.tableId then return '' end
     if not nestedSelector.tableId then return '' end


Строка 219: Строка 218:


-- Формирование списка химии
-- Формирование списка химии
getChemOutput = function(data, id)
local getChemOutput = function(data, id)
     local item = findDataById(data, id)
     local item = findDataById(buildIndex(data), id)
     if not item or not item.SolutionContainerManager or not item.SolutionContainerManager.solutions then return '' end
     if not item or not item.SolutionContainerManager or not item.SolutionContainerManager.solutions then return '' end


Строка 239: Строка 238:
     if not id then return 'Не указан ID.' end
     if not id then return 'Не указан ID.' end


     local data = loadData('User:IanComradeBot/prototypes/fills/Item.json')
     local data, dataIndex = loadData('User:IanComradeBot/prototypes/fills/Item.json')
    local dataIndex = buildIndex(data)
 
     if not data then return 'Не удалось загрузить данные.' end
     if not data then return 'Не удалось загрузить данные.' end


Строка 266: Строка 263:
         local entity = findDataById(dataIndex, id)
         local entity = findDataById(dataIndex, id)
         if not entity then return 'ID не найден в данных.' end
         if not entity then return 'ID не найден в данных.' end
 
         if entity.EntityTableContainerFill then
         if entity.EntityTableContainerFill then
             local containers = entity.EntityTableContainerFill.containers
             local containers = entity.EntityTableContainerFill.containers
Строка 275: Строка 272:


         return 'Режим rolls не найден для этого ID.'
         return 'Режим rolls не найден для этого ID.'
    else
    else
         return 'Неизвестный режим: ' .. mode
         return 'Неизвестный режим: ' .. mode
     end
     end