|
| 1 | +function parseClassArgs(args, obj) |
| 2 | +% Helper function for parsing args for class constructors. |
| 3 | +% |
| 4 | +% This is a variant of the 'parseArgs' function, and can be used to |
| 5 | +% automatically set object properties from a set of arguments passed into |
| 6 | +% a class constructor. |
| 7 | +% |
| 8 | +% Note that, in contrast to 'parseArgs', key names are case-sensitive. Also, |
| 9 | +% this function automatically detects whether an argument is a flag, by |
| 10 | +% reading the current value of the corresponding property: if this is a logical |
| 11 | +% scalar, the argument is assumed to be a flag. |
| 12 | +% |
| 13 | +% INPUT: |
| 14 | +% args = 'args' 1xN cell array |
| 15 | +% obj = object receiving property values |
| 16 | + |
| 17 | +curArgIdx = 1; |
| 18 | +while curArgIdx <= length(args) |
| 19 | + if ischar(args{curArgIdx}) |
| 20 | + if ~isprop(obj, args{curArgIdx}) |
| 21 | + error('Invalid argument "%s": No property found with that name', args{curArgIdx}); |
| 22 | + end |
| 23 | + |
| 24 | + % Identify flag arguments by the data type of their |
| 25 | + % corresponding property: |
| 26 | + if islogical(obj.(args{curArgIdx})) && isscalar(obj.(args{curArgIdx})) |
| 27 | + if (curArgIdx+1) <= length(args) && islogical(args{curArgIdx+1}) && isscalar(args{curArgIdx+1}) |
| 28 | + % Value is given explicitly |
| 29 | + obj.(args{curArgIdx}) = args{curArgIdx+1}; |
| 30 | + curArgIdx = curArgIdx + 1; |
| 31 | + else |
| 32 | + % No value given, so turn the flag ON |
| 33 | + obj.(args{curArgIdx}) = true; |
| 34 | + end |
| 35 | + else |
| 36 | + % Non-flag properties: value should be given |
| 37 | + if (curArgIdx+1) <= length(args) |
| 38 | + obj.(args{curArgIdx}) = args{curArgIdx+1}; |
| 39 | + curArgIdx = curArgIdx + 1; |
| 40 | + else |
| 41 | + error('Argument error: No value specified for argument "%s"', args{curArgIdx}); |
| 42 | + end |
| 43 | + end |
| 44 | + else |
| 45 | + error('Invalid argument at position %d: String expected', curArgIdx); |
| 46 | + end |
| 47 | + |
| 48 | + curArgIdx = curArgIdx + 1; |
| 49 | +end |
| 50 | + |
| 51 | +end |
| 52 | + |
0 commit comments