模块:SMWUtils

来自iFx Wiki
VIFF讨论 | 贡献2021年1月3日 (日) 03:05的版本
跳到导航 跳到搜索

此模块的文档可以在模块:SMWUtils/doc创建

local p = {}

function p.exists(query)
    return mw.smw.ask(query.."|limit=1")
end

function p.query_pages(query)
    local res = mw.smw.getQueryResult(query)
    local ret = {}
    for j, r in ipairs(res.results) do
        table.insert(ret, r.fulltext)
    end
    return ret
end

function p.query_page_properties(query, properties)
    local real_query = query
    for i, p in ipairs(properties) do
        real_query = real_query .. "|?" .. p
    end
    local res = mw.smw.getQueryResult(real_query)
    local ret = {}
    for i, r in ipairs(res.results) do
        local ans = {}
        local title = r.fulltext
        for j, prop in ipairs(properties) do
            local p_values = {}
            if r.printouts[prop] then
                for k, t in ipairs(r.printouts[prop]) do
                    table.insert(p_values, t.fulltext)
                end
            end
            ans[prop] = p_values
        end
        table.insert(ret, {title=title, properties=ans})
    end
    return ret
end

local QueryBuilder = {content = ""}

function QueryBuilder:new()
    local n = {}
    setmetatable(n, QueryBuilder)
    self.__index = self
    return n
end
function QueryBuilder:cat(v)
    local n = self:new()
    n.content = self.content .. v
    return n
end
function QueryBuilder:bracket(t)
    return self:cat('[['..t..']] ')
end
function QueryBuilder:or_()
    return self:cat(' OR ')
end
function QueryBuilder:done()
    return self.content
end
function QueryBuilder:page(name)
    return self:bracket(name)
end
function QueryBuilder:category(name)
    return self:bracket("Category:"..name)
end
function QueryBuilder:exists(prop)
    return self:bracket(prop..'::+')
end
function QueryBuilder:property(prop, value)
    return self:bracket(prop..'::'..value)
end

p.builder = QueryBuilder

return p