Module:DatasetLoader: Difference between revisions

// via Wikitext Extension for VSCode
// via Wikitext Extension for VSCode
Line 2: Line 2:
-- Central loader for Data: JSON assets via JsonConfig or mw.loadData, cached per render
-- Central loader for Data: JSON assets via JsonConfig or mw.loadData, cached per render


local loader = {}
local DatasetLoader = {}
local cache = {}


-- Returns a Lua table for the named dataset, or {} on failure
-- Retrieve a dataset by name (without extension). Returns a Lua table or {}.
function loader.get(name)
function DatasetLoader.get(name)
     -- Try JsonConfig extension first
     -- Return cached if available
     if mw.ext and mw.ext.data and mw.ext.data.get then
    if cache[name] then
        local ok, data = pcall(mw.ext.data.get, name)
        return cache[name]
         if ok and data then
    end
             return data
 
    -- 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


     -- Fallback to mw.loadJsonData for Data: namespace
     -- Default to empty table on any failure
     if mw.loadJsonData then
     if not data or type(data) ~= 'table' then
        local ok2, data2 = pcall(mw.loadJsonData, 'Data:' .. name .. '.json')
         data = {}
        if ok2 and data2 and type(data2) == 'table' then
            return data2
         end
     end
     end


     -- Ultimate fallback: empty table
     -- Cache and return
     return {}
    cache[name] = data
     return data
end
end


return loader
return DatasetLoader