跳转到内容

模組:Loop

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

这是本页的一个历史版本,由SunAfterRain留言 | 贡献2024年1月23日 (二) 06:07编辑。这可能和当前版本存在着巨大的差异。

local p = {}
local mYesno
local mTemplateParameters

local function yesno(value)
	if not mYesno then
		mYesno = require('Module:Yesno')
	end
	return mYesno(value)
end
	
local function loop(default_loopRange, validate_condition, stop_condition)
	return function (frame)	
		local args = frame.args
		local loopStart = tonumber(args['start'])
		local loopEnd = tonumber(args['end'])
		local loopContent = args.content
		if loopStart == loopEnd or not loopContent then
			return ''
		end
		local loopRange = tonumber(args['range']) or default_loopRange
		validate_condition(loopStart, loopEnd, loopRange)
		if yesno(args.delnowiki) then
			loopContent = mw.text.unstripNoWiki(loopContent)
		end
		if yesno(args.delmsgnw) then
			loopContent = mw.text.decode(loopContent)
		end
		if yesno(args.usingConditionalExpressions) then
			if not mTemplateParameters then
				mTemplateParameters = require('Module:TemplateParameters')
			end
			loopContent = mTemplateParameters._get_escape(loopContent)
		end
		local i = loopStart
		local output = ''
		local check_stop = stop_condition(loopStart, loopEnd, loopRange)
		while true do
			output = output .. loopContent:gsub('{{{1}}}', tostring(i))
			i = i + loopRange
			if check_stop(i) then
				break
			end
		end
		return mw.getCurrentFrame():preprocess(output)
	end
end

local _increment = loop(
	-- default_loopRange
	1,
	-- validate_condition
	function (loopStart, loopEnd, loopRange)
		if loopStart > loopEnd or loopRange < 0 then
			error('Only increment syntax allowed.')
		end
	end,
	-- stop_condition
	function (loopStart, loopEnd, loopRange)
		return function (i)
			return i > loopEnd
		end
	end
)

function p.increment(frame)
	return _increment(frame)
end

local _decrement = loop(
	-- default_loopRange
	-1,
	-- validate_condition
	function (loopStart, loopEnd, loopRange)
		if loopStart < loopEnd or loopRange > 0 then
			error('Only decrement syntax allowed.')
		end
	end,
	-- stop_condition
	function (loopStart, loopEnd, loopRange)
		return function (i)
			return i < loopEnd
		end
	end
)

function p.decrement(frame)
	return _decrement(frame)
end

return p