Module:LocGetString: Difference between revisions
From Heroes of Might and Magic: Olden Era Official Wiki
No edit summary |
No edit summary |
||
| (4 intermediate revisions by the same user not shown) | |||
| Line 47: | Line 47: | ||
function p.getText(frame) | function p.getText(frame) | ||
local sid = frame.args["sid"] | local sid = frame.args["sid"] or frame.args[1] | ||
local lang = frame.args["lang"] or "en" | local lang = frame.args["lang"] or "en" | ||
| Line 71: | Line 71: | ||
function p.translate(frame) | function p.translate(frame) | ||
local textEn = frame.args.text | local textEn = frame.args.text or frame.args[1] | ||
local lang = frame.args.lang or "en" | local lang = frame.args.lang or "en" | ||
| Line 78: | Line 78: | ||
end | end | ||
if lang == "en" then return textEn end | if lang == "en" then return textEn end | ||
local sid = buildRevEn()[textEn] | local sid = buildRevEn()[textEn] | ||
if not sid then return textEn end | if not sid then return textEn end | ||
return getLangData(lang)[sid] or textEn | return getLangData(lang)[sid] or textEn | ||
end | end | ||
return p | return p | ||
Latest revision as of 17:56, 16 November 2025
Documentation for this module may be created at Module:LocGetString/doc
local p = {}
local langCache = {} -- кеш по языкам
local revEnCache = nil -- кеш терминов
local DEBUG = false -- true - if testing
local function getLangData(lang)
if langCache[lang] then return langCache[lang] end
local title = mw.title.new("Data:LocStrings/" .. lang .. ".json")
local content = title and title:getContent() or ""
if content == "" then
langCache[lang] = {}
return langCache[lang]
end
local ok, data = pcall(mw.text.jsonDecode, content)
if not ok or type(data) ~= "table" then
langCache[lang] = {}
return langCache[lang]
end
local tokens = {}
local tokenList = data.tokens or {}
for _, item in ipairs(tokenList) do
if item.sid and item.text then
tokens[item.sid] = item.text
end
end
langCache[lang] = tokens
return tokens
end
local function buildRevEn()
if revEnCache then return revEnCache end
local MAX_LEN = 50 -- only shorts strings
revEnCache = {}
for sid, text in pairs(getLangData("en")) do
if #text <= MAX_LEN then
revEnCache[text] = sid
end
end
return revEnCache
end
function p.getText(frame)
local sid = frame.args["sid"] or frame.args[1]
local lang = frame.args["lang"] or "en"
if not sid then
return DEBUG and "No sid provided" or ""
end
local tokens = getLangData(lang)
local text = tokens[sid]
-- fallback на английский
if not text and lang ~= "en" then
text = getLangData("en")[sid]
end
if not text then
return DEBUG and ("SID not found: " .. sid) or ""
end
return text
end
function p.translate(frame)
local textEn = frame.args.text or frame.args[1]
local lang = frame.args.lang or "en"
if not textEn or #textEn == 0 or #textEn > 50 then
return textEn or ""
end
if lang == "en" then return textEn end
local sid = buildRevEn()[textEn]
if not sid then return textEn end
return getLangData(lang)[sid] or textEn
end
return p


