Module:GameText/loaddata

From The Stars Above Mod Wiki
Jump to navigation Jump to search

Documentation for this module may be created at Module:GameText/loaddata/doc

-- Some extracted localizations have dots in their keys.
-- Here we preprocess/convert the db's keys to supported ones
--
-- f.e. : 
-- {
-- ["Key.Subkey.Sub-subkey"] = "String",
-- }
-- converts to:
-- {
--  ["Key"] = {
--   ["Subkey"] = {
--    ["Sub-subkey"]= "String",
--   }
--  }
-- }
local function preprocess(data)
	local result = {}
	
	for key, value in pairs(data) do
		if type(key) == 'string' and string.find(key, '%.') then
			local splitted_key = mw.text.split(key, '%.')
			local old_key = table.remove(splitted_key, 1) -- remove the first index
			local new_key = table.concat(splitted_key, '.')
			result[old_key] = preprocess({ [new_key] = value })
		elseif type(value) == 'table' then
			result[key] = preprocess(value)
		else
			result[key] = value
		end
	end
	
	return result ~= {} and result or nil
end

local cache = mw.ext.LuaCache

return {
	load = function(mod)
		local status, result = pcall(function ()
			return mw.text.jsonDecode(cache.get(':_gametext:mod:' .. mod), mw.text.JSON_PRESERVE_KEYS)
		end)
		if status then
			return result
		else
			local data = preprocess(require('Module:GameText/db-' .. mod) or {})
			local jsonStr = mw.text.jsonEncode(data or {}, mw.text.JSON_PRESERVE_KEYS)
			
			cache.set( ':_gametext:mod:' .. mod, jsonStr)
			return data
		end
	end,
	
	purge = function(frame)
		local mod = type(frame) == 'string' and frame or frame.args[1]
		cache.delete(':_gametext:mod:' .. mod)
	end,
}