Command Line Subcommands in GDScript

Here’s the translation of the Go code to GDScript, formatted in Markdown suitable for Hugo:

Our first program will demonstrate how to create subcommands with their own sets of flags. This is similar to how command-line tools like git have different subcommands (e.g., git commit, git push) with their own options.

extends SceneTree

func _init():
    # We declare subcommands and their flags
    var foo_cmd = {
        "name": "foo",
        "enable": false,
        "name_value": ""
    }
    
    var bar_cmd = {
        "name": "bar",
        "level": 0
    }

    # The subcommand is expected as the first argument to the program
    if OS.get_cmdline_args().size() < 1:
        print("expected 'foo' or 'bar' subcommands")
        quit()

    # Check which subcommand is invoked
    var subcommand = OS.get_cmdline_args()[0]
    
    match subcommand:
        "foo":
            parse_foo_args(foo_cmd)
            print("subcommand 'foo'")
            print("  enable:", foo_cmd.enable)
            print("  name:", foo_cmd.name_value)
            print("  tail:", OS.get_cmdline_args().slice(3, OS.get_cmdline_args().size()))
        "bar":
            parse_bar_args(bar_cmd)
            print("subcommand 'bar'")
            print("  level:", bar_cmd.level)
            print("  tail:", OS.get_cmdline_args().slice(2, OS.get_cmdline_args().size()))
        _:
            print("expected 'foo' or 'bar' subcommands")
            quit()

    quit()

func parse_foo_args(cmd):
    var args = OS.get_cmdline_args()
    for i in range(1, args.size()):
        match args[i]:
            "--enable":
                cmd.enable = true
            "--name":
                if i + 1 < args.size():
                    cmd.name_value = args[i + 1]

func parse_bar_args(cmd):
    var args = OS.get_cmdline_args()
    for i in range(1, args.size()):
        if args[i].begins_with("--level="):
            cmd.level = int(args[i].split("=")[1])

To run this program, save it as command_line_subcommands.gd and use the Godot command-line interface:

$ godot --script command_line_subcommands.gd foo --enable --name joe a1 a2
subcommand 'foo'
  enable: true
  name: joe
  tail: [a1, a2]

$ godot --script command_line_subcommands.gd bar --level=8 a1
subcommand 'bar'
  level: 8
  tail: [a1]

Note that GDScript doesn’t have built-in command-line argument parsing like Go’s flag package. We’ve implemented a basic parsing mechanism to demonstrate the concept. In a real-world scenario, you might want to use a more robust argument parsing solution or create a more comprehensive custom implementation.

Also, GDScript is typically used within the Godot game engine, so running it as a standalone script like this is not a common use case. However, this example demonstrates how you could implement command-line-like behavior in a Godot project or tool.

Next, we’ll look at environment variables, another common way to parameterize programs.