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 Center および File ExchangeFunction Creation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by