Модуль:Prototypes/Объект/Торгомат: различия между версиями

Материал из Space Station 14 Вики
Нет описания правки
мНет описания правки
 
(не показано 67 промежуточных версий этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local restockData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/restock.json/data")
local inventoriesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")
local p = {}
local p = {}


-- Функция для загрузки данных из JSON-файла
-- Поиск данных по ID
local function loadData(filePath)
    local page = mw.title.new(filePath)
    local content = page:getContent()
    return content and mw.text.jsonDecode(content) or nil
end
 
-- Функция для поиска данных по ID
local function findDataById(data, id)
local function findDataById(data, id)
    if not data then return nil end
if not data then return nil end
    for _, item in ipairs(data) do
for _, item in ipairs(data) do
        if item.id == id then
if item.id == id then
            return item
return item
        end
end
    end
end
    return nil
return nil
end
end


-- Функция для получения списка содержимого автомата
-- Формирование вывода инвентаря
local function getInventory(id)
local function formatInventoryOutput(inventoryData)
    -- Загрузка данных
local result = ""
    local vendingMachines = loadData("User:IanComradeBot/prototypes/vending machines.json")
for itemId, count in pairs(inventoryData) do
    local inventories = loadData("User:IanComradeBot/prototypes/vending machines/inventories.json")
result = result .. mw.getCurrentFrame():preprocess("{{#invoke:Предмет|main|" .. itemId .. "|[" .. count .. "]|repository=|wrapper=}}")
 
end
    -- Поиск автомата по ID
return result ~= "" and result or "Инвентарь пуст."
    local vendingMachine = findDataById(vendingMachines, id)
    if not vendingMachine then return "" end
 
    -- Поиск инвентаря по pack
    local inventory = findDataById(inventories, vendingMachine.pack)
    if not inventory then return "" end
 
    -- Формирование строки с содержимым автомата
    local inventoryString = ""
    for item, quantity in pairs(inventory.startingInventory) do
        inventoryString = inventoryString .. "* " .. item .. ": " .. quantity .. "\n"
    end
 
    return inventoryString
end
end


-- Функция для получения списка доступов
-- Получение инвентаря автомата
local function getAccessList(id)
local function getInventoryOutput(id, mode)
    -- Загрузка данных
local vendingMachine = findDataById(vendingMachinesData, id)
    local vendingMachines = loadData("User:IanComradeBot/prototypes/vending machines.json")
if not vendingMachine then return "Автомат с таким ID не найден." end


    -- Поиск автомата по ID
local inventoryId = vendingMachine.VendingMachine and vendingMachine.VendingMachine.pack
    local vendingMachine = findDataById(vendingMachines, id)
if not inventoryId then return "Инвентарь не найден." end
    if not vendingMachine or not vendingMachine.AccessReader or not vendingMachine.AccessReader.access then
        return ""
    end


    -- Извлечение доступа
local inventory = findDataById(inventoriesData, inventoryId)
    local accessList = mw.text.jsonDecode(vendingMachine.AccessReader.access)
if not inventory then return "Данные об инвентаре отсутствуют." end
    if not accessList then return "" end


    -- Формирование строки для передачи в модуль Prototypes/Механика/Доступ
if mode == "inventory" and inventory.startingInventory then
    local accessString = ""
return formatInventoryOutput(inventory.startingInventory)
    for _, access in ipairs(accessList) do
elseif mode == "contraband" and inventory.contrabandInventory then
        -- Если элемент является таблицей, извлекаем строковое значение
return formatInventoryOutput(inventory.contrabandInventory)
        if type(access) == "table" then
elseif mode == "emag" and inventory.emaggedInventory then
            access = access[1]  -- Предполагаем, что нужное значение находится в первом элементе таблицы
return formatInventoryOutput(inventory.emaggedInventory)
        end
end
        -- Убедитесь, что access является строкой перед конкатенацией
        if type(access) == "string" then
            accessString = accessString .. "[[\"" .. access .. "\"]],"
        end
    end


    return '{{#invoke:Prototypes/Механика/Доступ|parse|[' .. accessString .. ']}}'
return "Не имеет дополнительного ассортимента."
end
end


-- Функция для получения ID пополнителя
-- Получение информации о пополнителе автомата
local function getRestockId(id)
local function getRestockOutput(id)
    -- Загрузка данных
local vendingMachine = findDataById(vendingMachinesData, id)
    local vendingMachines = loadData("User:IanComradeBot/prototypes/vending machines.json")
if not vendingMachine then return "" end
    local restocks = loadData("User:IanComradeBot/prototypes/vending machines/restock.json")


    -- Поиск автомата по ID
local packId = vendingMachine.VendingMachine and vendingMachine.VendingMachine.pack
    local vendingMachine = findDataById(vendingMachines, id)
    if not vendingMachine then return "" end


    -- Поиск пополнителя по pack
for _, restock in ipairs(restockData) do
    local restock = findDataById(restocks, vendingMachine.pack)
    local restockInfo = restock.VendingMachineRestock
    if not restock then return "" end
    if restockInfo and restockInfo.canRestock then
        for _, restockPack in ipairs(restockInfo.canRestock) do
            if restockPack == packId then
                return mw.getCurrentFrame():preprocess("{{Предмет|" .. restock.id .. "|size=64px|link=|repository=|wrapper=}}")
            end
        end
    end
end


    -- Формирование строки с ID пополнителя
return "Не имеет пополнителя."
    local restockString = restock.id or ""
    return restockString
end
end


-- Основная функция модуля
-- Основная функция модуля
function p.main(frame)
function p.main(frame)
    local id = frame.args.id
local mode = frame.args[1]
    local mode = frame.args.mode or ""  -- Определяем, что за режим: 'access', 'inventory' или 'restock'
local id = frame.args[2]


    if not id then
if not id then return "" end
        return ""
    end


    -- В зависимости от значения mode выбираем нужную функцию
if mode == "inventory" or mode == "contraband" or mode == "emag" then
    if mode == "access" then
return getInventoryOutput(id, mode)
        return getAccessList(id)
elseif mode == "restock" then
    elseif mode == "inventory" then
return getRestockOutput(id)
        return getInventory(id)
else
    elseif mode == "restock" then
return ""
        return getRestockId(id)
end
    else
        return ""
    end
end
end


return p
return p

Текущая версия от 10:38, 4 апреля 2025

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

-- Загрузка данных
local vendingMachinesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local restockData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/restock.json/data")
local inventoriesData = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")

local p = {}

-- Поиск данных по ID
local function findDataById(data, id)
	if not data then return nil end
	for _, item in ipairs(data) do
		if item.id == id then
			return item
		end
	end
	return nil
end

-- Формирование вывода инвентаря
local function formatInventoryOutput(inventoryData)
	local result = ""
	for itemId, count in pairs(inventoryData) do
		result = result .. mw.getCurrentFrame():preprocess("{{#invoke:Предмет|main|" .. itemId .. "|[" .. count .. "]|repository=|wrapper=}}")
	end
	return result ~= "" and result or "Инвентарь пуст."
end

-- Получение инвентаря автомата
local function getInventoryOutput(id, mode)
	local vendingMachine = findDataById(vendingMachinesData, id)
	if not vendingMachine then return "Автомат с таким ID не найден." end

	local inventoryId = vendingMachine.VendingMachine and vendingMachine.VendingMachine.pack
	if not inventoryId then return "Инвентарь не найден." end

	local inventory = findDataById(inventoriesData, inventoryId)
	if not inventory then return "Данные об инвентаре отсутствуют." end

	if mode == "inventory" and inventory.startingInventory then
		return formatInventoryOutput(inventory.startingInventory)
	elseif mode == "contraband" and inventory.contrabandInventory then
		return formatInventoryOutput(inventory.contrabandInventory)
	elseif mode == "emag" and inventory.emaggedInventory then
		return formatInventoryOutput(inventory.emaggedInventory)
	end

	return "Не имеет дополнительного ассортимента."
end

-- Получение информации о пополнителе автомата
local function getRestockOutput(id)
	local vendingMachine = findDataById(vendingMachinesData, id)
	if not vendingMachine then return "" end

	local packId = vendingMachine.VendingMachine and vendingMachine.VendingMachine.pack

	for _, restock in ipairs(restockData) do
	    local restockInfo = restock.VendingMachineRestock
	    if restockInfo and restockInfo.canRestock then
	        for _, restockPack in ipairs(restockInfo.canRestock) do
	            if restockPack == packId then
	                return mw.getCurrentFrame():preprocess("{{Предмет|" .. restock.id .. "|size=64px|link=|repository=|wrapper=}}")
	            end
	        end
	    end
	end

	return "Не имеет пополнителя."
end

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

	if not id then return "" end

	if mode == "inventory" or mode == "contraband" or mode == "emag" then
		return getInventoryOutput(id, mode)
	elseif mode == "restock" then
		return getRestockOutput(id)
	else
		return ""
	end
end

return p