Модуль:Ftl: различия между версиями
Материал из Space Station 14 Вики
Pok (обсуждение | вклад) Нет описания правки Метка: ручная отмена |
Pok (обсуждение | вклад) мНет описания правки |
||
(не показана 1 промежуточная версия этого же участника) | |||
Строка 1: | Строка 1: | ||
local p = {} | local p = {} | ||
-- Загрузка данных | -- Глобальный кэш данных и индекса | ||
local cachedData = nil | |||
local cachedIndex = nil | |||
-- Загрузка данных из JSON | |||
local function loadData(filePath) | local function loadData(filePath) | ||
local page = mw.title.new(filePath) | if not cachedData then | ||
local page = mw.title.new(filePath) | |||
local content = page and page:getContent() | |||
cachedData = content and mw.text.jsonDecode(content) or nil | |||
end | |||
return cachedData | |||
end | end | ||
-- | -- Создание индекса для быстрого поиска по ключам | ||
local function | local function buildIndex(data) | ||
for | if not cachedIndex then | ||
cachedIndex = {} | |||
for categoryName, category in pairs(data) do | |||
for key, value in pairs(category) do | |||
cachedIndex[key] = value | |||
end | |||
end | end | ||
end | end | ||
return nil | return cachedIndex | ||
end | |||
-- Поиск текста по ключу через индекс | |||
local function findTextByKey(index, key) | |||
return index[key] or nil | |||
end | end | ||
-- Поиск ключа по тексту | -- Поиск ключа по тексту (всё ещё перебор, но он используется реже) | ||
local function findKeyByText(data, text) | local function findKeyByText(data, text) | ||
for categoryName, category in pairs(data) do | for categoryName, category in pairs(data) do | ||
Строка 28: | Строка 43: | ||
end | end | ||
return nil | return nil | ||
end | |||
-- Получение всех строк из категории | |||
local function getCategoryStrings(data, categoryName) | |||
local category = data[categoryName] | |||
if not category then | |||
return nil | |||
end | |||
local result = {} | |||
for _, value in pairs(category) do | |||
if type(value) == "string" then | |||
table.insert(result, value) | |||
end | |||
end | |||
return result | |||
end | end | ||
Строка 44: | Строка 76: | ||
return 'Ошибка: Невозможно загрузить данные из JSON.' | return 'Ошибка: Невозможно загрузить данные из JSON.' | ||
end | end | ||
-- Построение индекса (если требуется) | |||
local index = buildIndex(data) | |||
if mode == "translation" then | if mode == "translation" then | ||
local result = findTextByKey( | local result = findTextByKey(index, param) | ||
return result or "Ошибка: Ключ не найден." | return result or "Ошибка: Ключ не найден." | ||
elseif mode == "key" then | elseif mode == "key" then | ||
local result = findKeyByText(data, param) | local result = findKeyByText(data, param) | ||
return result or "Ошибка: Текст не найден." | return result or "Ошибка: Текст не найден." | ||
elseif mode == "categories" then | |||
local strings = getCategoryStrings(data, param) | |||
if not strings or #strings == 0 then | |||
return "Ошибка: Категория не найдена или пуста." | |||
end | |||
local output = {} | |||
for _, value in ipairs(strings) do | |||
table.insert(output, "<li>" .. mw.text.encode(value) .. "</li>") | |||
end | |||
return table.concat(output) | |||
else | else | ||
return "Ошибка: Неизвестный режим работы." | return "Ошибка: Неизвестный режим работы." |
Версия от 08:53, 29 января 2025
Для документации этого модуля может быть создана страница Модуль:Ftl/doc
local p = {} -- Глобальный кэш данных и индекса local cachedData = nil local cachedIndex = nil -- Загрузка данных из JSON local function loadData(filePath) if not cachedData then local page = mw.title.new(filePath) local content = page and page:getContent() cachedData = content and mw.text.jsonDecode(content) or nil end return cachedData end -- Создание индекса для быстрого поиска по ключам local function buildIndex(data) if not cachedIndex then cachedIndex = {} for categoryName, category in pairs(data) do for key, value in pairs(category) do cachedIndex[key] = value end end end return cachedIndex end -- Поиск текста по ключу через индекс local function findTextByKey(index, key) return index[key] or nil end -- Поиск ключа по тексту (всё ещё перебор, но он используется реже) local function findKeyByText(data, text) for categoryName, category in pairs(data) do for key, value in pairs(category) do if value == text then return key end end end return nil end -- Получение всех строк из категории local function getCategoryStrings(data, categoryName) local category = data[categoryName] if not category then return nil end local result = {} for _, value in pairs(category) do if type(value) == "string" then table.insert(result, value) end end return result end -- Основная функция модуля function p.main(frame) local mode = frame.args[1] local param = frame.args[2] if not mode or not param then return "Ошибка: Не указаны все необходимые параметры." end -- Загрузка данных из JSON local data = loadData('User:IanComradeBot/ftl/ru-RU.json') if not data or type(data) ~= 'table' then return 'Ошибка: Невозможно загрузить данные из JSON.' end -- Построение индекса (если требуется) local index = buildIndex(data) if mode == "translation" then local result = findTextByKey(index, param) return result or "Ошибка: Ключ не найден." elseif mode == "key" then local result = findKeyByText(data, param) return result or "Ошибка: Текст не найден." elseif mode == "categories" then local strings = getCategoryStrings(data, param) if not strings or #strings == 0 then return "Ошибка: Категория не найдена или пуста." end local output = {} for _, value in ipairs(strings) do table.insert(output, "<li>" .. mw.text.encode(value) .. "</li>") end return table.concat(output) else return "Ошибка: Неизвестный режим работы." end end return p