跳转到内容

模組:Namespace/ForEach

本页使用了标题或全文手工转换
维基百科,自由的百科全书

这是Module:Namespace/ForEach当前版本,由SunAfterRain留言 | 贡献编辑于2022年11月3日 (四) 12:25。这个网址是本页该版本的固定链接。

(差异) ←上一修订 | 最后版本 (差异) | 下一修订→ (差异)

local p = {}
local getArgs = require('Module:Arguments').getArgs
local mError = require('Module:Error')
local mTemplateParameters = require('Module:TemplateParameters')
local yesno = require('Module:Yesno')

local data = mw.loadData('Module:Namespace/data')

local function formatStringWrap(str, args, forcePreprocess)
	if not mw.ustring.match(str, '{') then
		return str
	end
	local result = mTemplateParameters._getFormatingStringByArgument(str, args)
	if mw.ustring.match(result, '{') and forcePreprocess then
		result = mw.getCurrentFrame():preprocess(result)
	end
	return result
end

local function tryInvoke(expr, args, forcePreprocess)
	if type(expr) == type(tryInvoke) then
		return expr(args, forcePreprocess)
	end

	return formatStringWrap(tostring(expr), args, forcePreprocess)
end

function p._format(template, cond, reverse)
	cond = cond or function () return true end
	reverse = reverse or false
	local output = ''
	local function forEach(nsid)
		local nsData = mw.site.namespaces[nsid]
		if yesno(tryInvoke(cond, {nsid = nsid}, true)) then
			output = output .. tryInvoke(template, {nsid = nsid, ns = nsData.name})
		end
	end
	if reverse then
		for index = #data.Namespace.list, 1, -1 do
			forEach(data.Namespace.list[index])
		end
	else
		for _, nsid in ipairs(data.Namespace.list) do
			forEach(nsid)
		end
	end
	return output
end

function p._main(args)
	local template = args.template or args.format or args[1] or args['1']
	local cond = args.cond or args[2] or args['2'] or 'false'
	local delnowiki = yesno(args.delnowiki)
	local delmsgnw = yesno(args.delmsgnw)
	local reverse = yesno(args.reverse)

	if not template or template == '' then
		error('沒有提供渲染模板。')
	end
	if delnowiki then
		template = mw.text.unstripNoWiki(template)
		cond = mw.text.unstripNoWiki(cond)
	end
	if delmsgnw then
		template = mw.text.decode(template)
		cond = mw.text.unstripNoWiki(cond)
	end
	
	return mw.getCurrentFrame():preprocess(p._format(template, cond, reverse))
end

function p.main(frame)
	local args = getArgs(frame)
	local status, result = pcall(p._main, args)
	return status and result or mError.error{'[[Module:Namespace/ForEach]]錯誤:' .. result}
end

return p