Created
December 5, 2022 04:38
-
-
Save rbrins/4b349d0df715e2ce8b9c675b74471620 to your computer and use it in GitHub Desktop.
Brief Basic Argument Parsing in Nim with comment explanations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# default variables that could be modified from cmd arguments (if needed /desired) | |
var portNum: int = 443 | |
# CLI Arguments for the Server | |
# in nim argument values must be passed with = or : | |
# Brief Basic Arugment Parsing in Nim, probably not for production arg parsing | |
# see documentation page for slightly more details: https://nim-lang.org/docs/parseopt.html | |
# each argument token has a kind, a key, and val. | |
# ... kind being the type of argument, cmdEnd signaling the end of the command line | |
# ... key being the name | |
# ... val being the key's value provided or empty string | |
# getopt: is for iterating over the arguments with it returning the tuple with kind, key, val | |
# ... https://nim-lang.org/docs/parseopt.html#getopt | |
for kind, key, value in getopt(): # we do this because it is a tuple of three returned | |
# kind (CmdLineKind): this is the type of argument seen, cmdArgument, cmdLongOption, or cmdShortOption | |
# our first case switch because it dictates how we process the argument (since cmdArgument doesnt have a value) | |
case kind | |
# cmdArgument is without the "-" in the arguments, | |
# like nim c ./file.nim, the c is a cmdArgument | |
of cmdArgument: | |
# echo "Got arg with key: ", key | |
discard #(should discard this iteration of the loop and move to the next one) | |
# cmdLongOption, cmdShortOption: | |
of cmdLongOption, cmdShortOption: | |
case key | |
# -p is to specify port number as in -p=443 or -p:443 but not -p 443 | |
of "p": | |
# echo "Got arg 'p' with value: ", value | |
# change the port value string, to an int & store in portNum variable defined above | |
discard parseInt(value, portNum, 0) | |
of cmdEnd: | |
discard # this was the final iteration, so we discard this and move on to after the loop now |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment