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

조회 수: 6 (최근 30일)
DEK800W6
DEK800W6 2016년 1월 27일
편집: jgg 2016년 1월 29일
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