Commits

Mathias Panzenböck  committed 68bfd77

optparse: support Object instances in addition to Array instances for record options

  • Participants
  • Parent commits 33d4917

Comments (0)

Files changed (1)

  *                   the object and you get the value of the field
  *
  *      // Type: record
+ *      create:      function () -> object, default: Array
  *      args:        array of type definitions (type part of option definitions)
  *
  *      // Type: custom
 				var metavar = [];
 				for (i in optdef.args) {
 					var arg = optdef.args[i];
+					if (arg.target === undefined) {
+						arg.target = i;
+					}
 					this._initType(arg, name+'['+i+']');
 	
 					if (arg.argc < 1) {
 						return onOption.apply(this, values);
 					};
 				}
+				if (optdef.create === undefined) {
+					optdef.create = Array;
+				}
 				optdef.parse = function () {
-					var values = [];
+					var values = this.create();
 					var parserIndex = 0;
 					for (var i = 0; i < arguments.length;) {
 						var arg = optdef.args[parserIndex ++];
 						for (var j = 0; j < arg.argc; ++ j) {
 							raw.push(arguments[i+j]);
 						}
-						var value = arg.parse.apply(arg, raw);
-						values.push(value);
+						values[arg.target] = arg.parse.apply(arg, raw);
 						i += arg.argc;
 					}
 					return values;
 function stringifyRecord (record) {
 	var buf = [];
 	for (var i = 0; i < this.args.length; ++ i) {
-		buf.push(this.args[i].stringify(record[i]));
+		var arg = this.args[i];
+		buf.push(arg.stringify(record[arg.target]));
 	}
 	return buf.join(' ');
 }
 		onOption: function (str, rec) {
 			console.log('args: '+JSON.stringify(str)+', '+JSON.stringify(rec));
 		}});
+	parser.add('--named', {type: 'record',
+		create: Object,
+		default: {a: 0.5, b: 300, c: 'bla'},
+		args: [
+			{type: 'float',   target: 'a'},
+			{type: 'integer', target: 'b'},
+			{type: 'string',  target: 'c'}
+		]});
 
 	var data = parser.parse();