Line Filters in Lua

Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. In this case, it will write a capitalized version of all input text. You can use this pattern to write your own Lua line filters.

-- Import required modules
local string = require("string")

-- Main function
local function main()
    -- In Lua, we can read input line by line directly
    for line in io.lines() do
        -- Convert the line to uppercase
        local ucl = string.upper(line)
        
        -- Write out the uppercased line
        print(ucl)
    end
end

-- Call the main function
main()

In this Lua version:

  1. We don’t need to import a separate module for I/O operations as they are part of the Lua standard library.

  2. Lua’s io.lines() function provides an iterator that reads input line by line, similar to the scanner in the original example.

  3. We use the string.upper() function to convert each line to uppercase.

  4. Lua doesn’t have a separate error handling mechanism for I/O operations like this. If there’s an error reading from stdin, it will typically raise an error that will terminate the program.

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

This Lua script provides the same functionality as the original example, reading input line by line, converting each line to uppercase, and printing the result.