Module:DatasetLoader: Difference between revisions
// via Wikitext Extension for VSCode |
// via Wikitext Extension for VSCode |
||
| (6 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
-- | --[[ | ||
* Name: DatasetLoader | |||
* Author: Mark W. Datysgeld | |||
* Description: Central loader for Data: JSON assets via JsonConfig or mw.loadData, cached per render | |||
* Notes: Tries JsonConfig extension first, then falls back to mw.loadData from Data: namespace; caches results to improve performance | |||
]] | |||
local | local DatasetLoader = {} | ||
local cache = {} | |||
-- Returns a Lua table | -- Retrieve a dataset by name (without extension). Returns a Lua table or {}. | ||
function | function DatasetLoader.get(name) | ||
-- | -- Return cached if available | ||
if | if cache[name] then | ||
return cache[name] | |||
if | end | ||
-- Ensure filename has .json extension | |||
local fullName = name | |||
if not fullName:match('%.%w+$') then | |||
fullName = fullName .. '.json' | |||
end | |||
local data | |||
-- Try JsonConfig extension (mw.ext.data.get) | |||
local success, result = pcall(function() | |||
return mw.ext.data.get(fullName) | |||
end) | |||
if success and type(result) == 'table' then | |||
data = result | |||
else | |||
-- Fallback to mw.loadData from Data: namespace | |||
success, result = pcall(function() | |||
return mw.loadData('Data:' .. fullName) | |||
end) | |||
if success and type(result) == 'table' then | |||
data = result | |||
end | end | ||
end | end | ||
-- | -- Default to empty table on any failure | ||
if not data or type(data) ~= 'table' then | |||
data = {} | |||
end | end | ||
-- | -- Cache and return | ||
return | cache[name] = data | ||
return data | |||
end | end | ||
return | return DatasetLoader | ||