Why does inputParser allow a required argument to also be input as a name-value pair?

6 次查看(过去 30 天)
In R2013b, with a mix of addRequired and addParameter definitions, if the user happens to supply a name-value pair using the same name as the required argument, the value from the name-value pair takes precedence. Example code:
function [] = parsertest( req, varargin )
p = inputParser;
p.addRequired( 'req' );
p.addParameter( 'opt1', 1 );
p.parse( req, varargin{:} );
p.Results
end
>> parsertest( 'a', 'req', 'x')
ans =
opt1: 1
req: 'x'
Since 'req' was not specified with addParameter, I would expect this to throw an error rather than req taking on the value 'x'.
Another situation I would think would cause an error is if multiple instances of 'req', are supplied. Instead, the last instance wins:
>> parsertest( 'a', 'req', 'x', 'req', 'y', 'req', 'z')
ans =
opt1: 1
req: 'z'
Are these behaviors expected?
  1 个评论
jgg
jgg 2016-1-27
编辑:jgg 2016-1-29
Wow, this is not at all how I expected this would work. It seems that the addParameter name-pair is somehow taking precedence over the required name-pair, despite the name for the required parameter being entirely internal to the input parser object. This definitely looks like a bug to me, especially since I cannot find any option or setting to control this behaviour. Bumping for priority.
EDIT1: I replicated in this R2015A as well, so it's not version specific. I think it's also a security concern, since if you have validation on addRequired but not on addParameter, you could inject values into the "required" value while skipping validation.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by