2

I want to build a list step by step, adding or not adding certain strings to the list based on the values of some variables.

I am writing a package that runs an executable and it has variables that can be used to configure behavior by deciding whether or not I add some arguments to the command.

When I'm about to call the tool, I want to build the command as a list (list argv[0] argv[1]...) which I use in (make-process :command (repos--create-command). I got it to work and went on to write the rest of my package but this seems wrong

(defun repos--create-command () ;; Add-to-list adds to the front ;; Also some guy who looks like he gets LISP says add-to-list isn't good ;; for building a list the way I want. (let ((args (list))) (when repos-overview-all (add-to-list 'args "-all")) (when repos-overview-n-jobs (add-to-list 'args (number-to-string repos-overview-n-jobs)) (add-to-list 'args "-j")) (when (not repos-overview-ignore) (add-to-list 'args "-noignore")) (unless repos-overview-fetch (add-to-list 'args "--no-fetch")) (if (boundp 'other-config-file) (add-to-list 'args other-config-file) (add-to-list 'args repos-config-file)) (add-to-list 'args "-F") (add-to-list 'args repos-command) args)) 

The idea is that when some variable is true, I will add --all to the arguments, if repos-overview-njobs is non-nil, I will add -j N where N is the value of repos-overview-n-jobs.

1
  • @shynur answered the question. Your code would work if you had a (defvar arg), making arg a special (dynamic) variable. The let binding would then affect that dynamic variable instead of a lexical variable, so add-to-list would work. But the right approach is, as Shynur said, to use push or cl-pushnew instead of add-to-list. Commented Feb 20 at 19:30

1 Answer 1

3

The documentation for add-to-list:

(add-to-list LIST-VAR ELEMENT &optional APPEND COMPARE-FN)

LIST-VAR should not refer to a lexical variable.

So use push instead. (Then use reverse if you want to reverse it.)

2
  • Thank you. I did (let (args (list)) (when ... (push _ args))... (nreverse args)) with the pushes in the reverse order from the code in my question. If I understand correctly, in my particular case, nreverse is OK because I don't care about destroying args. Commented Feb 20 at 21:02
  • @PhilippeCarphin: You understand correctly. It's OK to use it if you're sure you don't care about destroying args. Commented Feb 21 at 1:22

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.