Module:Command

From Modded Wiki
Revision as of 16:28, 17 February 2014 by minecraft>Majr (Correctly support optional parameters)
Jump to navigation Jump to search

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

local p = {}
function p.cmd( f )
	local args = f:getParent().args
	local syntax = mw.loadData( 'Module:Command/Syntax' )
	local command
	
	args[1] = mw.text.trim( args[1] )
	if args[1]:find( '%s' ) or not syntax[args[1]] then
		command = { args[1]:match( '^([^%s]-)%s(.+)$' ) }
		
		if #command == 0 then
			command = { args[1], args[2] }
		end
	end
	if not command then
		command = { args[1] }
	end
	command[1] = command[1]:lower()
	
	if args[2] and syntax[args[1]] then
		local fullCommand
		for _, v in ipairs( args ) do
			if v == '...' then
				fullCommand = true
			end
		end
		
		local arg = 1
		function parseParams( params, sub )
			local section = {}
			local hasValue
			for i, v in ipairs( params ) do
				if type( v ) == 'table' then
					local subSection, subHasValue = parseParams( v, true )
					if subHasValue then
						hasValue = true
					end
					table.insert( section, subSection )
				else
					arg = arg + 1
					
					-- Skip "..." arg
					if args[arg] and args[arg] == '...' then
						arg = arg + 1
					end
					
					if args[arg] then
						hasValue = true
						args[arg] = mw.text.trim( args[arg] )
						if args[arg] ~= '' and args[arg] ~= '?' then
							args[arg] = args[arg]:gsub( '<', '&lt;' )
							table.insert( section, args[arg] )
						end
					end
					if not section[i] then
						table.insert( section, v )
					end
				end
			end
			section = table.concat( section, ' ' )
			
			if sub and not hasValue then
				if fullCommand then
					section = '(' .. section .. ')'
				else
					section = nil
				end
			end
			
			return section, hasValue
		end
		
		command[2] = parseParams( syntax[syntax[command[1]]] or syntax[command[1]] )
	end
	
	if args.link then
		if args.link:lower() ~= 'none' then
			command[1] = '[[' .. args.link .. '|' .. command[1] .. ']]'
		end
	else
		command[1] = '[[Commands#' .. command[1] .. '|' .. command[1] .. ']]'
	end
	
	local slash = '/'
	if args['/'] == '0' or args.slash == '0' then
		slash = ''
	end
	
	local attr
	if args.long == '1' then
		attr = 'style="display:block;padding:0.8em 1em;margin-bottom:0.4em;word-wrap:break-word"'
	else
		attr = 'class="nowrap"'
	end
	
	return '<code ' .. attr .. '>' .. slash .. table.concat( command, ' ' ) .. '</code>'
end
return p