Module:Page

このモジュールについての説明文ページを Module:Page/doc に作成できます
local _M = {};

function _M.clean(title)
    local string = mw.ustring;
    
    title = string.gsub( title, '^%s*%[*%[%[(.-)%]%]%]*%s*$', function(l)
        return string.gsub( l, '^([^|]*)|.*$', '%1', 1 )
    end, 1 )
        :gsub( '[%s_]+', ' ' )
        :gsub( '/+', '/' )
        :gsub( '^%s', '', 1 )
        :gsub( '%s$', '', 1 )
        :gsub( '/$', '', 1 );
    
    if title == '' then
        return tostring( mw.title.getCurrentTitle() );
    elseif string.sub( title, 1, 1) == '/' then
        return table.concat{ tostring( mw.title.getCurrentTitle() ), title };
    else
        return title;
    end
end

-- subpages = require('Module:Page').subpages
-- for page in subpages('Page', [{options}]) do ... end

function _M.subpages(title, options )
    local title, options, pattern = _M.clean(title), options or {};
    
    pattern, title = pcall(mw.title.new, title, 0);
    if not pattern or not title then
        return ipairs({});
    elseif not options.ignoreNS and not mw.site.namespaces[title.namespace].hasSubpages then
        return ipairs({});
    end
    
    options.ignoreNS = nil;
    pattern = table.concat{ string.rep( '.', string.len( title.text ) ), '/', '([^\r\n]+)\r?\n' };
    title = title.prefixedText;
    local frame, expand, decode = mw:getCurrentFrame(), mw.text.unstrip, mw.text.decode;
    local function get(name, options, pattern )
        local params = {};
        for k,v in pairs(options) do
            table.insert( params, table.concat{ k, '=', v ~= nil and tostring(v) or '' } );
        end
        params = table.concat( params, '|' );
        if params ~= "" then params = table.concat{ '|', params }; end
        params = expand( frame:preprocess( string.format('{{special:prefixindex/%s/%s}}', name, params) ) );
        params = string.gsub( params, '%b<>', function(tag) return tag == '</a>' and '\n' or ''; end );
        options = {}
        for k in string.gmatch( params, pattern ) do table.insert( options, decode(k) ); end
        return options;
    end;
    local subpages = get( title, options, pattern );
    
    return function(title, last)
        local page;
        while true do
            page = table.remove( subpages, 1 );
            if page ~= nil then return page, last; end
            options.from = table.concat{ title, '/', last };
            subpages = get( title, options, pattern );
            table.remove( subpages, 1 );
            if #subpages == 0 then
                return nil;
            end
        end
    end, title;
end

return _M
最終更新日時 2014年3月30日 (日) 00:09