Create and run a Gosu program that processes arguments

A Gosu program that you run from the command prompt can read arguments from the command line and report errors in the values of those arguments.

Procedure

  1. Choose a directory in which to save your command-prompt tool. In this directory, create a subdirectory called test, which is the package name.
  2. Create a Gosu class that defines your properties. The following code defines two properties, one String property named Name and a boolean property named Hidden:
    package test
    
    class Args { 
      // String argument
      static var _name : String as Name = "No name"
    
      // boolean argument -- No value to set on the command line
      static var _hidden : boolean as Hidden = false
    }
  3. Save this Gosu class file as the file Args.gs in the test directory.
  4. Create a Gosu program, using the following code:
    uses test.*
    var args = Gosu.RawArgs
    var numArgs = args.Count
    
    try {
      if (arg.startsWith( "-" )) {
        if ((arg == "-name") and (i< numArgs-1)) {Args.Name = args[i+1]}
        if (arg == "-hidden") {Args.Hidden = (i< numArgs-1) and (args[i+1] == "false")?false:true}
      }
    } catch (Exception) {
      print("Error parsing args: " + args)
    }
    
    print("hello " + Args.Name)
    print("you are " + (Args.Hidden ? "hidden" : "visible") + "!!!!")
  5. Click Save As and save this new command-prompt tool as myaction.gsp in the directory that contains the test subdirectory.
  6. Open a command-prompt window and navigate to the directory that contains myaction.gsp.
  7. In the command-prompt window, enter the following command
    gosu -classpath "." myaction.gsp -name John -hidden
    This command prints:
    hello John
    you are hidden!!!!