URim (обсуждение | вклад) (Попытка 11 блять) |
URim (обсуждение | вклад) (Я сбился со счёту) |
||
| Строка 6: | Строка 6: | ||
-- Кэш для хранения данных о химических веществах | -- Кэш для хранения данных о химических веществах | ||
local chemCache = nil | local chemCache = nil | ||
-- Функция для логирования | |||
local function log(message) | |||
mw.log("DEBUG: " .. message) | |||
end | |||
-- Функция для загрузки данных о рецептах из JSON-файла | -- Функция для загрузки данных о рецептах из JSON-файла | ||
| Строка 17: | Строка 22: | ||
end) | end) | ||
if success then | if success and type(data) == "table" then | ||
recipeCache = data | recipeCache = data | ||
return data | return data | ||
else | else | ||
log("Ошибка при загрузке JSON (mealrecipes_prototypes.json): " .. tostring(data)) | |||
return {} | return {} | ||
end | end | ||
| Строка 36: | Строка 41: | ||
end) | end) | ||
if success then | if success and type(data) == "table" then | ||
chemCache = data | chemCache = data | ||
return data | return data | ||
else | else | ||
log("Ошибка при загрузке JSON (chem_prototypes.json): " .. tostring(data)) | |||
return {} | return {} | ||
end | end | ||
| Строка 49: | Строка 54: | ||
local translatedName = frame:callParserFunction{ name = '#invoke', args = { 'Entity_Lookup', 'getname', id } } | local translatedName = frame:callParserFunction{ name = '#invoke', args = { 'Entity_Lookup', 'getname', id } } | ||
if translatedName then | if translatedName then | ||
return string.format("%s [[Файл:%s.png| | return string.format("%s [[Файл:%s.png|32px]]", translatedName, id) | ||
else | else | ||
return id -- Если перевод не найден, возвращаем исходный ID | return id -- Если перевод не найден, возвращаем исходный ID | ||
| Строка 85: | Строка 90: | ||
else | else | ||
return ingredientName | return ingredientName | ||
end | |||
end | |||
-- Функция для сортировки рецептов | |||
local function sortRecipes(sortedRecipes, recipeType, frame) | |||
if recipeType == "grindableRecipes" then | |||
table.sort(sortedRecipes, function(a, b) | |||
local aName = translateID(frame, a.data.input or "") | |||
local bName = translateID(frame, b.data.input or "") | |||
return aName < bName | |||
end) | |||
else | |||
table.sort(sortedRecipes, function(a, b) | |||
local aName = translateID(frame, a.data.result or "") | |||
local bName = translateID(frame, b.data.result or "") | |||
return aName < bName | |||
end) | |||
end | end | ||
end | end | ||
| Строка 91: | Строка 113: | ||
p.fillRecipeTable = function(frame) | p.fillRecipeTable = function(frame) | ||
local args = frame.args | local args = frame.args | ||
local recipeType = args.recipeType or "microwaveRecipes" | local recipeType = args.recipeType or "microwaveRecipes" | ||
local templateName = args.template or "RecipeRow" | local templateName = args.template or "RecipeRow" | ||
local out = "" | local out = "" | ||
| Строка 107: | Строка 129: | ||
for recipeId, recipe in pairs(recipes[recipeType]) do | for recipeId, recipe in pairs(recipes[recipeType]) do | ||
table.insert(sortedRecipes, { id = recipeId, data = recipe }) | table.insert(sortedRecipes, { id = recipeId, data = recipe }) | ||
-- Ограничим количество рецептов для тестирования | |||
if #sortedRecipes >= 10 then | |||
break | |||
end | |||
end | end | ||
-- Сортировка рецептов | -- Сортировка рецептов | ||
sortRecipes(sortedRecipes, recipeType, frame) | |||
-- Перебираем отсортированные рецепты | -- Перебираем отсортированные рецепты | ||
| Строка 161: | Строка 175: | ||
} | } | ||
-- Обработка для | -- Обработка для других типов рецептов | ||
else | |||
-- Добавьте обработку для других типов рецептов | |||
end | end | ||
Версия от 00:23, 9 марта 2025
Для документации этого модуля может быть создана страница Модуль:TableOfRecipes/doc
local p = {}
-- Кэш для хранения данных о рецептах
local recipeCache = nil
-- Кэш для хранения данных о химических веществах
local chemCache = nil
-- Функция для логирования
local function log(message)
mw.log("DEBUG: " .. message)
end
-- Функция для загрузки данных о рецептах из JSON-файла
local function loadRecipes()
if recipeCache then
return recipeCache
end
local success, data = pcall(function()
return mw.text.jsonDecode(mw.title.new("User:CapybaraBot/mealrecipes_prototypes.json"):getContent())
end)
if success and type(data) == "table" then
recipeCache = data
return data
else
log("Ошибка при загрузке JSON (mealrecipes_prototypes.json): " .. tostring(data))
return {}
end
end
-- Функция для загрузки данных о химических веществах из JSON-файла
local function loadChemPrototypes()
if chemCache then
return chemCache
end
local success, data = pcall(function()
return mw.text.jsonDecode(mw.title.new("User:CapybaraBot/chem_prototypes.json"):getContent())
end)
if success and type(data) == "table" then
chemCache = data
return data
else
log("Ошибка при загрузке JSON (chem_prototypes.json): " .. tostring(data))
return {}
end
end
-- Функция для перевода ID с использованием Module:Entity Lookup (для твердых веществ)
local function translateID(frame, id)
local translatedName = frame:callParserFunction{ name = '#invoke', args = { 'Entity_Lookup', 'getname', id } }
if translatedName then
return string.format("%s [[Файл:%s.png|32px]]", translatedName, id)
else
return id -- Если перевод не найден, возвращаем исходный ID
end
end
-- Функция для перевода реагента (жидкого вещества) из chem_prototypes.json
local function translateReagent(reagentId)
local chemData = loadChemPrototypes()
if chemData[reagentId] and chemData[reagentId].name then
return chemData[reagentId].name
else
return reagentId -- Если перевод не найден, возвращаем исходный ID
end
end
-- Функция для проверки, можно ли приготовить ингредиент
local function isIngredientCookable(ingredientId)
local recipes = loadRecipes()
for _, recipeGroup in pairs(recipes) do
for _, recipe in pairs(recipeGroup) do
if recipe.result == ingredientId then
return true
end
end
end
return false
end
-- Функция для создания ссылки на рецепт, если ингредиент можно приготовить
local function createIngredientLink(frame, ingredientId, ingredientName)
local anchor = string.gsub(ingredientId, " ", "_") -- Заменяем пробелы на подчеркивания
if isIngredientCookable(ingredientId) then
return string.format('[[#%s|%s]]', anchor, ingredientName)
else
return ingredientName
end
end
-- Функция для сортировки рецептов
local function sortRecipes(sortedRecipes, recipeType, frame)
if recipeType == "grindableRecipes" then
table.sort(sortedRecipes, function(a, b)
local aName = translateID(frame, a.data.input or "")
local bName = translateID(frame, b.data.input or "")
return aName < bName
end)
else
table.sort(sortedRecipes, function(a, b)
local aName = translateID(frame, a.data.result or "")
local bName = translateID(frame, b.data.result or "")
return aName < bName
end)
end
end
-- Основная функция для генерации таблицы с рецептами
p.fillRecipeTable = function(frame)
local args = frame.args
local recipeType = args.recipeType or "microwaveRecipes"
local templateName = args.template or "RecipeRow"
local out = ""
-- Загрузка данных о рецептах
local recipes = loadRecipes()
if not recipes or not recipes[recipeType] then
return "Ошибка: данные о рецептах не загружены или тип рецептов не найден."
end
-- Создаем таблицу для сортировки
local sortedRecipes = {}
for recipeId, recipe in pairs(recipes[recipeType]) do
table.insert(sortedRecipes, { id = recipeId, data = recipe })
-- Ограничим количество рецептов для тестирования
if #sortedRecipes >= 10 then
break
end
end
-- Сортировка рецептов
sortRecipes(sortedRecipes, recipeType, frame)
-- Перебираем отсортированные рецепты
for _, recipeData in ipairs(sortedRecipes) do
local recipe = recipeData.data
local templateArgs = {}
-- Обработка для microwaveRecipes
if recipeType == "microwaveRecipes" then
-- Переводим результат
local result = translateID(frame, recipe.result) or "Нет результата"
-- Формируем список ингредиентов (solids)
local solidsList = {}
if recipe.solids and type(recipe.solids) == "table" then
for solidId, amount in pairs(recipe.solids) do
local ingredientName = translateID(frame, solidId)
ingredientName = createIngredientLink(frame, solidId, ingredientName)
table.insert(solidsList, string.format("%s (%d)", ingredientName, amount))
end
end
-- Формируем список реагентов (reagents)
local reagentsList = {}
if recipe.reagents and type(recipe.reagents) == "table" then
for reagentId, amount in pairs(recipe.reagents) do
local reagentName = translateReagent(reagentId)
table.insert(reagentsList, string.format("%s (%d)", reagentName, amount))
end
end
-- Формируем аргументы для шаблона
templateArgs = {
result = result,
solids = table.concat(solidsList, ", ") or "Нет ингредиентов",
reagents = table.concat(reagentsList, ", ") or "Нет реагентов",
time = recipe.time or "Нет данных"
}
-- Обработка для других типов рецептов
else
-- Добавьте обработку для других типов рецептов
end
-- Добавляем якорь для строки таблицы
out = out .. string.format('|- id="%s"\n', recipe.id)
-- Генерация строки таблицы с использованием шаблона
out = out .. frame:expandTemplate{ title = templateName, args = templateArgs } .. "\n"
end
return out
end
return p