如果前面的验证函数都不够,那么还有类inputParser,其可以执行极其复杂的函数输入检查。
p = inputParser () ¶创建inputParser类的对象p。
此类的设计目的是允许轻松解析函数参数。该类支持四种类型的参数:
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参数参数都可以紧随其后。只有Parameter和Switch参数可以混合在一起,并且它们必须出现在前两种类型之后。
注2:如果两者都有Optional和Parameter参数混合在函数API中,一旦字符串可选参数未能验证,它将被视为Optional参数。剩余的参数视为Parameter或Switch参数。
版权所有 © 2024-2025 Octave中文网
ICP备案/许可证号:黑ICP备2024030411号-2