Line Filters in AngelScript

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 AngelScript that writes a capitalized version of all input text. You can use this pattern to write your own AngelScript line filters.

#include <string>
#include <stdio>

void main()
{
    string line;
    
    // Read input line by line
    while (readLine(line))
    {
        // Convert the line to uppercase
        string upperLine = line.toUpper();
        
        // Write out the uppercased line
        print(upperLine + "\n");
    }
    
    // Check for errors during reading
    if (error)
    {
        print("error: " + getExceptionInfo() + "\n");
    }
}

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 | angelscript line-filters.as
HELLO
FILTER

In this AngelScript version:

  1. We include the necessary modules for string manipulation and I/O operations.

  2. The main() function is the entry point of our script.

  3. We use a while loop with readLine() to read input line by line. This is similar to the bufio.Scanner in the original example.

  4. The string.toUpper() method is used to convert each line to uppercase.

  5. We use print() to output the uppercased line.

  6. Error handling is done using the global error variable and getExceptionInfo() function, which is AngelScript’s way of handling exceptions.

Note that AngelScript doesn’t have built-in functionality for command-line arguments or file I/O, so this example assumes these operations are provided by the host application. The exact implementation might vary depending on how AngelScript is integrated into your environment.