Module:RootFinder

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

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

-- Module:LanguageTree
local p = {}

-- Finds the root language by following the "Is Variety Of" property chain
function p.findRootLanguage(frame, languageName)
    local currentLanguage = languageName
    local visited = {}
    
    while currentLanguage and not visited[currentLanguage] do
        visited[currentLanguage] = true
        
        -- Query to get the parent language
        local query = "[[" .. currentLanguage .. "]]|?Is Variety Of"
        local result = frame:preprocess('{{#ask:' .. query .. '}}')
        
        -- Extract parent language from the result
        local parent = nil
        for line in result:gmatch("[^\r\n]+") do
            local parentMatch = line:match("Is Variety Of:%s*(.+)")
            if parentMatch and parentMatch:gsub("%s+", "") ~= "" then
                parent = parentMatch:gsub("^%s*(.-)%s*$", "%1") -- Trim whitespace
                break
            end
        end
        
        if not parent or parent == "" then
            -- No parent found, this is the root language
            return currentLanguage
        else
            -- Move up to the parent language
            currentLanguage = parent
        end
    end
    
    -- Handle potential circular reference
    return currentLanguage
end

-- Main function to generate the language tree
function p.main(frame)
    -- Get the language name from the frame parameters
    local languageName = frame.args[1]
    
    if not languageName or languageName == "" then
        return "Error: No language name provided"
    end
    
    -- Find the root language
    local rootLanguage = p.findRootLanguage(frame, languageName)
    
    -- Construct the query for the tree
    local treeQuery = "[[Category:Language]]|format=tree|parent=Is Variety Of|limit=5000|root=" .. rootLanguage
    
    -- Execute the query using #ask and return the result
    return frame:preprocess('{{#ask:' .. treeQuery .. '}}')
end

return p