Module:RootFinder

From The Seven Sages of Rome
Revision as of 11:05, 25 March 2025 by Noeth (talk | contribs)

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

local p = {}

-- Function to find the root language
function p.findRootLanguage(frame, languageName)
    local rootLanguage = languageName
    local varietyProperty = "Is Variety Of"
    local maxIterations = 10  -- Prevent infinite loops
    local iterations = 0
    
    while iterations < maxIterations do
        -- Construct a query to find the parent language
        local askQuery = string.format('{{#ask: [[%s]][[%s::+]] |?%s |limit=1 |format=list}}', 
            mw.text.encode(rootLanguage), varietyProperty, varietyProperty)
        
        local parentLanguage = frame:preprocess(askQuery):match("^%s*(.-)%s*$")
        
        -- If no parent language is found, we've reached the root
        if parentLanguage == "" or parentLanguage == nil then
            break
        end
        
        -- Update the root language to the parent
        rootLanguage = parentLanguage
        iterations = iterations + 1
    end
    
    return rootLanguage
end

-- Main function to generate the language tree
function p.languageTree(frame)
    local languageName = frame.args[1]
    
    if not languageName or languageName == "" then
        return "No language name provided"
    end
    
    -- Find the root language
    local rootLanguage = p.findRootLanguage(frame, languageName)
    
    -- Construct the tree query
    local treeQuery = string.format('[[Category:Language]] |format=tree |parent=Is Variety Of |limit=5000 |root=%s', 
        mw.text.encode(rootLanguage))
    
    -- Return the tree using preprocessing
    return frame:preprocess('{{#ask:' .. treeQuery .. '}}')
end

return p