Command Line Arguments


With the ability to load files, we can take the chance to add in some functionality typical of other programming languages. When file names are given as arguments to the command line we can try to run these files. For example to run a python file one might write python filename.py.

These command line arguments are accessible using the argc and argv variables that are given to main. The argc variable gives the number of arguments, and argv specifies each string. The argc is always set to at least one, where the first argument is always the complete command invoked.

That means if argc is set to 1 we can invoke the interpreter, otherwise we can run each of the arguments through the builtin_load function.

  1. /* Supplied with list of files */
  2. if (argc >= 2) {
  3. /* loop over each supplied filename (starting from 1) */
  4. for (int i = 1; i < argc; i++) {
  5. /* Argument list with a single argument, the filename */
  6. lval* args = lval_add(lval_sexpr(), lval_str(argv[i]));
  7. /* Pass to builtin load and get the result */
  8. lval* x = builtin_load(e, args);
  9. /* If the result is an error be sure to print it */
  10. if (x->type == LVAL_ERR) { lval_println(x); }
  11. lval_del(x);
  12. }
  13. }

It’s now possible to write some basic program and try to invoke it using this method.

  1. lispy example.lspy