如果前面的验证函数都不足够,那么还有类inputParser
其可以执行极其复杂的函数输入检查。
p =
inputParser ()
¶创建对象pinputsparser类的。
此类的设计目的是允许轻松解析函数参数。该类支持四种类型的参数:
addRequired
);addOptional
);addParameter
);addSwitch
).使用这些方法定义函数API后,可以使用parse
方法和使用访问的结果Results
访问者。
返回已定义的参数名称列表。(只读)
返回一个结构体,其参数名称为字段名称和相应的值。(只读)
返回类似于的结构体Results
,但对于未匹配的参数。(只读)详见KeepUnmatched
属性
返回具有使用默认值的参数名称的元胞数组。(只读)
= name
¶设置要在错误消息中使用的函数名称;默认为空字符串。
= boolean
¶设置参数名称的匹配是否应区分大小写;默认为false。
= boolean
¶设置是否解析与任何Parameter不匹配的字符串参数并将其存储在Unmatched
属性默认为false。如果为false,则在第一个无法识别的参数处将发出错误,分段将停止。请注意,从于Switch
和Parameter
参数可能是混杂的,不可能知道不匹配的参数的类型。Octave假设所有不匹配的参数都属于Parameter
类型,因此必须后跟一个值。
= boolean
¶设置是否为的参数名称Parameter
和Switch
只要名称唯一地标识了一个参数,就可以以缩写形式给出参数;默认为true。例如,参数'opt'
将匹配一个参数'opt_color'
,但如果还有一个参数,则会失败'opt_case'
.
= boolean
¶设置传递给函数的结构体是否扩展为参数/值对(parameter=fieldname);默认为true。
以下示例显示了如何使用此类:
function check (varargin) p = inputParser (); # create object p.FunctionName = "check"; # set function name p.addRequired ("pack", @ischar); # mandatory argument p.addOptional ("path", pwd(), @ischar); # optional argument ## Create anonymous function handle for validators valid_vec = @(x) isvector (x) && all (x >= 0) && all (x <= 1); p.addOptional ("vec", [0 0], valid_vec); ## Create two arguments of type "Parameter" vld_type = @(x) any (strcmp (x, {"linear", "quadratic"})); p.addParameter ("type", "linear", vld_type); vld_tol = @(x) any (strcmp (x, {"low", "medium", "high"})); p.addParameter ("tolerance", "low", vld_tol); ## Create a switch type of argument p.addSwitch ("verbose"); p.parse (varargin{:}); # Run created parser on inputs ## The rest of the function can access inputs by using p.Results. ## For example, get the tolerance input with p.Results.tolerance endfunction
check ("mech"); # valid, use defaults for other arguments check (); # error, one argument is mandatory check (1); # error, since ! ischar check ("mech", "~/dev"); # valid, use defaults for other arguments check ("mech", "~/dev", [0 1 0 0], "type", "linear"); # valid ## following is also valid. Note how the Switch argument type can ## be mixed in with or before the Parameter argument type (but it ## must still appear after any Optional arguments). check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high"); ## following returns an error since an Optional argument, 'path', ## was given after the Parameter argument 'type'. check ("mech", "type", "linear", "~/dev");
注1:一个函数可以有四种API类型的任何混合,但它们必须以特定的顺序出现。Required
参数必须是第一位的,任何参数都可以紧随其后Optional
参数。OnlythParameter
和Switch
参数可以混合在一起,并且它们必须出现在前两种类型之后。
注2:如果两者都有Optional
和Parameter
参数混合在函数API中,一旦字符串可选参数未能验证,它将被视为Optional
参数。将剩余的参数与任何Parameter
或Switch
参数。
版权所有 © 2024-2025 Octave中文网
ICP备案/许可证号:黑ICP备2024030411号-2