Line Filters in GDScript

A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.

Here’s an example line filter in GDScript that writes a capitalized version of all input text. You can use this pattern to write your own GDScript line filters.

extends SceneTree

func _init():
    # Create a new File object to read from stdin
    var stdin = File.new()
    stdin.open("user://stdin", File.READ)

    # Create a new File object to write to stdout
    var stdout = File.new()
    stdout.open("user://stdout", File.WRITE)

    # Read lines from stdin
    while not stdin.eof_reached():
        var line = stdin.get_line()
        
        # Convert the line to uppercase
        var ucl = line.to_upper()
        
        # Write out the uppercased line
        stdout.store_line(ucl)

    # Check for errors during reading
    if stdin.get_error() != OK:
        printerr("error: ", stdin.get_error())
        quit(1)

    # Close the files
    stdin.close()
    stdout.close()

    # Quit the application
    quit()

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | godot -s line_filters.gd
HELLO
FILTER

In this GDScript version, we’re using the File class to read from stdin and write to stdout. We open the files in the appropriate modes, read lines from stdin, convert them to uppercase, and write them to stdout.

Note that GDScript doesn’t have a direct equivalent to Go’s bufio.Scanner, so we’re using a while loop to read lines until we reach the end of the file. Also, error handling in GDScript is typically done using return codes, so we check the error status after reading.

To run this script, you would need to save it as line_filters.gd and run it using the Godot engine in script mode (godot -s).

Remember that this is a simplified example and may not handle all edge cases or large inputs as efficiently as the Go version. In a real-world scenario, you might want to implement more robust error handling and potentially use Godot’s streaming features for handling larger inputs.