URim (обсуждение | вклад) (Попытка 4) |
URim (обсуждение | вклад) (Исправлен перевод жиж) |
||
| Строка 1: | Строка 1: | ||
local p = {} | local p = {} | ||
-- Кэш для хранения данных о рецептах | |||
local recipeCache = nil | |||
-- Кэш для хранения данных о химических веществах | |||
local chemCache = nil | |||
-- Функция для загрузки данных о рецептах из JSON-файла | -- Функция для загрузки данных о рецептах из JSON-файла | ||
local function loadRecipes() | local function loadRecipes() | ||
if recipeCache then | |||
return recipeCache | |||
end | |||
local success, data = pcall(function() | local success, data = pcall(function() | ||
return mw.text.jsonDecode(mw.title.new("User:CapybaraBot/mealrecipes_prototypes.json"):getContent()) | return mw.text.jsonDecode(mw.title.new("User:CapybaraBot/mealrecipes_prototypes.json"):getContent()) | ||
| Строка 9: | Строка 18: | ||
if success then | if success then | ||
recipeCache = data | |||
return data | |||
else | |||
mw.log("Ошибка при загрузке JSON (mealrecipes_prototypes.json): " .. 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 then | |||
chemCache = data | |||
return data | return data | ||
else | else | ||
mw.log("Ошибка при загрузке JSON: " .. data) | mw.log("Ошибка при загрузке JSON (chem_prototypes.json): " .. data) | ||
return {} | return {} | ||
end | end | ||
end | end | ||
-- Функция для перевода ID с использованием Module:Entity Lookup | -- Функция для перевода ID с использованием Module:Entity Lookup (для твердых веществ) | ||
local function translateID(frame, id) | local function translateID(frame, id) | ||
return frame:callParserFunction{ name = '#invoke', args = { 'Entity_Lookup', 'getname', id } } | return frame:callParserFunction{ name = '#invoke', args = { 'Entity_Lookup', 'getname', id } } | ||
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 | end | ||
| Строка 49: | Строка 88: | ||
if recipe.reagents and type(recipe.reagents) == "table" then | if recipe.reagents and type(recipe.reagents) == "table" then | ||
for reagentId, amount in pairs(recipe.reagents) do | for reagentId, amount in pairs(recipe.reagents) do | ||
local reagentName = | local reagentName = translateReagent(reagentId) -- Используем новую функцию для перевода | ||
table.insert(reagentsList, string.format("%s (%d)", reagentName, amount)) | table.insert(reagentsList, string.format("%s (%d)", reagentName, amount)) | ||
end | end | ||
Версия от 05:10, 7 марта 2025
Для документации этого модуля может быть создана страница Модуль:TableOfRecipes/doc
local p = {}
-- Кэш для хранения данных о рецептах
local recipeCache = nil
-- Кэш для хранения данных о химических веществах
local chemCache = nil
-- Функция для загрузки данных о рецептах из 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 then
recipeCache = data
return data
else
mw.log("Ошибка при загрузке JSON (mealrecipes_prototypes.json): " .. 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 then
chemCache = data
return data
else
mw.log("Ошибка при загрузке JSON (chem_prototypes.json): " .. data)
return {}
end
end
-- Функция для перевода ID с использованием Module:Entity Lookup (для твердых веществ)
local function translateID(frame, id)
return frame:callParserFunction{ name = '#invoke', args = { 'Entity_Lookup', 'getname', id } }
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
-- Функция для генерации таблицы с рецептами
p.fillRecipeTable = function(frame)
local out = ""
-- Загрузка данных о рецептах
local recipes = loadRecipes()
if not recipes or not recipes.microwaveRecipes then
return "Ошибка: данные о рецептах не загружены."
end
for _, recipe in pairs(recipes.microwaveRecipes) do
-- Переводим результат
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)
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
-- Формируем аргументы для шаблона
local templateArgs = {
result = result, -- Результат становится названием строки
solids = table.concat(solidsList, ", ") or "Нет ингредиентов",
reagents = table.concat(reagentsList, ", ") or "Нет реагентов",
time = recipe.time or "Нет данных"
}
-- Генерация строки таблицы с использованием шаблона
out = out .. frame:expandTemplate{ title = "RecipeRow", args = templateArgs }
end
return out
end
return p