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

мНет описания правки
мНет описания правки
Строка 2: Строка 2:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Загрузка данных из разных модулей
-- Загрузка данных  
---------------------------------------------------------------------
---------------------------------------------------------------------
local itemData          = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local itemData          = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
Строка 24: Строка 24:
---------------------------------------------------------------------
---------------------------------------------------------------------


-- Функция для рекурсивного поиска id предмета в произвольной структуре таблицы.
local function searchItemInStructure(struct, targetId)
local function searchItemInStructure(struct, targetId)
     if type(struct) ~= "table" then
     if type(struct) ~= "table" then
Строка 43: Строка 42:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Обратный поиск по содержимому (reverseContained)
 
-- По заданному id предмета ищем таблицы, в которых он встречается,
-- а затем в itemData ищем хранилища, где используются найденные таблицы.
---------------------------------------------------------------------
---------------------------------------------------------------------
local function findRelatedTables(initialList)
    local results = {}
    local function recursiveSearch(tblId)
        if results[tblId] then
            return
        end
        results[tblId] = true
        for id, entry in pairs(tableData) do
            if type(entry) == "table" then
                for _, value in pairs(entry) do
                    if type(value) == "table" and value.tableId and value.tableId == tblId then
                        recursiveSearch(id)
                    end
                end
            end
        end
    end
    for _, tblId in ipairs(initialList) do
        recursiveSearch(tblId)
    end
    local res = {}
    for id in pairs(results) do
        table.insert(res, id)
    end
    return res
end
function p.reverseContained(frame)
function p.reverseContained(frame)
     local targetId = frame.args[2]
     local targetId = frame.args[2]
Строка 53: Строка 77:
     end
     end


     local matchingTables = {}
     local initialTables = {}
    -- Перебираем все записи таблиц
     for tableId, tblEntry in pairs(tableData) do
     for tableId, tblEntry in pairs(tableData) do
         if type(tblEntry) == "table" then
         if type(tblEntry) == "table" then
             if searchItemInStructure(tblEntry, targetId) then
             if searchItemInStructure(tblEntry, targetId) then
                 table.insert(matchingTables, tableId)
                 table.insert(initialTables, tableId)
             end
             end
         end
         end
     end
     end


     if #matchingTables == 0 then
     if #initialTables == 0 then
         return "Таблица, содержащая предмет с id " .. targetId .. ", не найдена."
         return "Таблица, содержащая предмет с id " .. targetId .. ", не найдена."
     end
     end
    local allRelatedTables = findRelatedTables(initialTables)


     local matchingStorages = {}
     local matchingStorages = {}
    -- Ищем в itemData хранилища, в которых используется найденная таблица
     for storageId, storage in pairs(itemData) do
     for storageId, storage in pairs(itemData) do
         if type(storage) == "table" and storage.EntityTableContainerFill and storage.EntityTableContainerFill.containers then
         if type(storage) == "table" and storage.EntityTableContainerFill and storage.EntityTableContainerFill.containers then
             local containers = storage.EntityTableContainerFill.containers
             local containers = storage.EntityTableContainerFill.containers
             if containers.entity_storage and containers.entity_storage.tableId then
             if containers.entity_storage and containers.entity_storage.tableId then
                 for _, tblId in ipairs(matchingTables) do
                 for _, tblId in ipairs(allRelatedTables) do
                     if containers.entity_storage.tableId == tblId then
                     if containers.entity_storage.tableId == tblId then
                         table.insert(matchingStorages, storageId)
                         table.insert(matchingStorages, storageId)
Строка 80: Строка 104:
             end
             end
             if containers.storagebase and containers.storagebase.tableId then
             if containers.storagebase and containers.storagebase.tableId then
                 for _, tblId in ipairs(matchingTables) do
                 for _, tblId in ipairs(allRelatedTables) do
                     if containers.storagebase.tableId == tblId then
                     if containers.storagebase.tableId == tblId then
                         table.insert(matchingStorages, storageId)
                         table.insert(matchingStorages, storageId)
Строка 86: Строка 110:
                 end
                 end
             end
             end
        end
        if storage.id and storage.id == targetId then
            table.insert(matchingStorages, storageId)
         end
         end
     end
     end
Строка 97: Строка 124:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Обратный поиск для экипировки (reverseEquipment)
 
-- По заданному id оборудования ищем, в каких наборах экипировки
-- оно используется, и, если найдено в startingGear, ищем в jobData
-- по параметру startingGear, выводя id соответствующего job.
---------------------------------------------------------------------
---------------------------------------------------------------------
function p.reverseEquipment(frame)
function p.reverseEquipment(frame)
     local targetId = frame.args[2]
     local targetId = frame.args[2]
     local slotFilter = frame.args[3] -- если указан, фильтруем по конкретному слоту
     local slotFilter = frame.args[3]
     if not targetId or targetId == "" then
     if not targetId or targetId == "" then
         return "Ошибка: не указан id оборудования для обратного поиска."
         return "Ошибка: не указан id оборудования для обратного поиска."
Строка 181: Строка 205:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Обратный поиск для груза (cargo) (reverseCargo)
 
-- Всегда осуществляется поиск по полю product.
---------------------------------------------------------------------
---------------------------------------------------------------------
function p.reverseCargo(frame)
function p.reverseCargo(frame)
Строка 205: Строка 228:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Обратный поиск для станков (lathe) (reverseLathe)
 
-- По заданному результату рецепта ищем рецепты станков и возвращаем id станка, который его производит.
---------------------------------------------------------------------
---------------------------------------------------------------------
local function getRecipeById(recipeId)
local function getRecipeById(recipeId)
Строка 224: Строка 246:


     local matchingLathes = {}
     local matchingLathes = {}
    -- Вспомогательная функция для проверки набора рецептов
     local function checkRecipes(recipeIds)
     local function checkRecipes(recipeIds)
         for _, recipeId in ipairs(recipeIds or {}) do
         for _, recipeId in ipairs(recipeIds or {}) do
Строка 260: Строка 281:


---------------------------------------------------------------------
---------------------------------------------------------------------
-- Обратный поиск в торговых автоматах по содержимому инвентаря
 
---------------------------------------------------------------------
---------------------------------------------------------------------
function p.reverseVending(frame)
function p.reverseVending(frame)
Строка 325: Строка 346:
---------------------------------------------------------------------
---------------------------------------------------------------------
-- Основная функция модуля
-- Основная функция модуля
-- Принимает первым аргументом режим обратного поиска:
-- reverseContained, reverseEquipment, reverseCargo, reverseLathe.
-- Второй (и последующие) аргументы передаются соответствующим функциям.
---------------------------------------------------------------------
---------------------------------------------------------------------
function p.main(frame)
function p.main(frame)