CLI Args

Shows how to read command line arguments. To pass an argument: roc main.roc some_argument or roc -- some_argument or roc build && ./main some_argument.

We also have a more complex example that uses a filename as argument.


# Run with `roc ./examples/CommandLineArgs/main.roc some_argument`
# !! This currently does not work in combination with --linker=legacy, see
app [main] {
    pf: platform "",

import pf.Stdout
import pf.Task
import pf.Arg

main =
    args = Arg.list! {} # {} is necessary as a temporary workaround

    # get the second argument, the first is the executable's path
    argResult = List.get args 1 |> Result.mapErr (\_ -> ZeroArgsGiven)

    when argResult is
        Err ZeroArgsGiven ->
            Task.err (Exit 1 "Error ZeroArgsGiven:\n\tI expected one argument, but I got none.\n\tRun the app like this: `roc main.roc -- input.txt`")

        Ok firstArgument ->
            Stdout.line "received argument: $(firstArgument)"


Run this from the directory that has main.roc in it:

$ roc main.roc some_argument
received argument: some_argument