Модуль:Песочница/Pok: различия между версиями

Нет описания правки
Нет описания правки
Строка 1: Строка 1:
-- Загрузка данных
local dataItem = mw.loadData("Модуль:Prototypes/Хранилище/Предмет/data")
local allSelectorData = mw.loadData("Модуль:Prototypes/Хранилище/Предмет/data2")
local p = {}
local p = {}


Строка 9: Строка 5:
     local result = {}
     local result = {}
     if rolls and rolls.range then
     if rolls and rolls.range then
        -- Если указан range
         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)
Строка 17: Строка 14:
         end
         end
     elseif rolls and rolls.value then
     elseif rolls and rolls.value then
        -- Если указано value
         result[#result + 1] = string.format('[%d]', rolls.value)
         result[#result + 1] = string.format('[%d]', rolls.value)
     else
     else
Строка 24: Строка 22:
end
end


-- Поиск данных по ID
-- Локальные функции
local function findDataById(dataItem, id)
local loadData, findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector
     for _, item in ipairs(dataItem) do
 
         if item.id == id then
-- Функция для загрузки данных (без кэширования)
            return item
loadData = function(filePath)
        end
    local page = mw.title.new(filePath)
    local content = page:getContent()
    return content and mw.text.jsonDecode(content) or nil
end
 
-- Функция для создания хэш-таблицы для быстрого поиска по ID (без кэширования)
local function buildIndex(data)
    if not data then return {} end
    local index = {}
     for _, item in ipairs(data) do
         index[item.id] = item
     end
     end
     return nil
     return index
end
 
-- Поиск данных по ID через индекс
findDataById = function(dataIndex, id)
    return dataIndex and dataIndex[id] or nil
end
end


-- Форматирование содержимого
-- Форматирование содержимого
local function formatContent(content)
formatContent = function(content)
     if not content.id then
     if not content.id then
         return "Ошибка: отсутствует id у элемента."
         return "Ошибка: отсутствует id у элемента."
Строка 42: Строка 55:
     local name = string.format('{{#invoke:Entity Lookup|getname|%s}}', content.id)
     local name = string.format('{{#invoke:Entity Lookup|getname|%s}}', content.id)
     local image = string.format('%s.png', content.id)
     local image = string.format('%s.png', content.id)
    local amount = (content.amount and content.amount ~= 1) and string.format(" [%d]", content.amount) or ""
local amount = (content.amount and content.amount ~= 1) and string.format(" [%d]", content.amount) or ""
     local prob = ""
     local prob = ""


Строка 58: Строка 71:
     )
     )
end
end
-- Локальные функции
local getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector


-- Получение содержимого через таблицу
-- Получение содержимого через таблицу
Строка 76: Строка 86:


     local results = {}
     local results = {}
    local nestedCache = {}


     for _, child in ipairs(children) do
     for _, child in ipairs(children) do
Строка 82: Строка 91:
             results[#results + 1] = formatContent(child)
             results[#results + 1] = formatContent(child)
         elseif child["!type"] == "NestedSelector" then
         elseif child["!type"] == "NestedSelector" then
             -- Кэшируем результат вызова handleNestedSelector
             results[#results + 1] = handleNestedSelector(child, true)
            if not nestedCache[child.tableId] then
                nestedCache[child.tableId] = handleNestedSelector(child, true)
            end
            results[#results + 1] = nestedCache[child.tableId]
         elseif child["!type"] == "GroupSelector" then
         elseif child["!type"] == "GroupSelector" then
             results[#results + 1] = handleGroupSelector(child)
             results[#results + 1] = handleGroupSelector(child)
Строка 97: Строка 102:
-- Обработка таблиц
-- Обработка таблиц
getTableOutput = function(tableId)
getTableOutput = function(tableId)
     local tableData = findDataById(allSelectorData, tableId)
    local allSelectors = loadData('User:IanComradeBot/prototypes/AllSelector.json')
     local tableData = findDataById(buildIndex(allSelectors), tableId)


     if not tableData then return 'Таблица не найдена.' end
     if not tableData then return 'Таблица не найдена.' end
Строка 111: Строка 117:


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


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


-- Формирование списка химии
-- Формирование списка химии
getChemOutput = function(dataItem, id)
getChemOutput = function(data, id)
     local item = findDataById(dataItem, id)
     local item = findDataById(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


Строка 238: Строка 244:


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


     if mode == 'framing' then
     if mode == 'framing' then
Строка 248: Строка 259:


         if subMode == 'chem' then
         if subMode == 'chem' then
             return frame:preprocess('{{СollapsibleMenu|' .. getChemOutput(dataItem, id) .. '}}')
             return frame:preprocess('{{СollapsibleMenu|' .. getChemOutput(dataIndex, id) .. '}}')
         elseif subMode == 'contained' then
         elseif subMode == 'contained' then
             return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(dataItem, id) .. '}}')
             return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(dataIndex, id) .. '}}')
         else
         else
             return 'Неизвестный подрежим для framing: ' .. subMode
             return 'Неизвестный подрежим для framing: ' .. subMode
         end
         end
     elseif mode == 'chem' then
     elseif mode == 'chem' then
         return frame:preprocess(getChemOutput(dataItem, id))
         return frame:preprocess(getChemOutput(dataIndex, id))
     elseif mode == 'contained' then
     elseif mode == 'contained' then
         return frame:preprocess(getContainedOutput(dataItem, id))
         return frame:preprocess(getContainedOutput(dataIndex, id))
     elseif mode == 'rolls' then
     elseif mode == 'rolls' then
         local entity = findDataById(dataItem, id)
         local entity = findDataById(dataIndex, id)
         if not entity then return 'ID не найден в данных.' end
         if not entity then return 'ID не найден в данных.' end