Dungeons and Dragons with escript and OptionParser

Sometimes you just need a random number generator. In this video, we build a command line executable to do that using escript and OptionParser. Let’s go over both of these before getting into it.

escript

An escript is an executable that can be invoked from the command line. An escript can run on any machine that has Erlang installed and by default does not require Elixir to be installed, as Elixir is embedded as part of the escript.

Source: https://hexdocs.pm/mix/1.0.5/Mix.Tasks.Escript.Build.html

With escript, we’ll be able to generate an executable that runs on the command line. We’ll be able to build that executable with mix escript.build.

OptionParser

Functions for parsing command line arguments.

When calling a command, it’s possible to pass command line options to modify what the command does. In this documentation, those are called “switches”, in other situations they may be called “flags” or simply “options”. A switch can be given a value, also called an “argument”.

Source: https://hexdocs.pm/elixir/OptionParser.html

Elixir’s OptionParser module allows us to parse arguments passed to a command line executable. We’ll be using it to extract out the arguments we need, notably the “—roll” argument and an integer to generate a random number against.

Our goal is to be able to run the following command to emulate rolling a d20:

./die_roller --roll 20

Which would output “You rolled a 18 on your d20”

Pretty good roll!

Sign up for our newsletter

Get notified of any new episodes as we release them.

© 2020 QuantLayer, LLC. All rights reserved.