Search code examples
lispautolisp

Return values with indexes from list in AutoLisp


I am trying to create a new list by taking values from the user. Then I want to display the values in this list along with their indexes. For example for the values 5,4,3,2 I want the output to be:

5 0

4 1

3 2

2 3

This is my code:

(setq n (getint "How many elements you want to input"))

(defun CreateList(n)
  (setq lista '())
  (repeat n
     (setq temp (getstring "Enter value"))
     (setq lista (append lista (list temp)))
  )
 (foreach el lista
    (print(strcat el vl-position el lista))
 )
)

(CreateList n)

As result I am getting: error: bad argument type: stringp #<SUBR @0000027b44742e88 VL-POSITION>

I have tried to change the print line to something like (print(strcat el (rtos vl-position el lista)))

But It didn't work also. Any ideas?


Solution

  • Firstly, a few comments about your code:

    (defun CreateList(n)
    

    Always declare your local variables as part of the defun expression - this will limit the scope of the variables to the function in which they are declared. Without limiting the scope of the variable, its value will be retained after the function has completed evaluation and this can lead to headaches such as that which I describe here.

    (setq lista '())
    

    If lista is declared as a local variable, there is no need to initialise it as an empty list, as the symbol will already have no initial value within the scope of the function.

    (setq temp (getstring "Enter value"))
    

    If you're always looking obtain integers (per your example), consider using the getint function in place of getstring.

    (setq lista (append lista (list temp)))
    

    When building lists, the use of cons is far more efficient, i.e.:

    (setq lista (cons temp lista))
    

    Note however, that this will build the list in reverse.

    (print(strcat el vl-position el lista))
    

    The above line contains the source of your error, specifically:

    (strcat el vl-position el lista)
    

    Here, vl-position is a function and not a string and so cannot be passed as an argument to the strcat function (similarly, neither can lista, which points to list data).

    Instead, vl-position should be enclosed in parentheses to form its own expression:

    (vl-position el lista)
    

    However, be aware that this approach may return undesired results if duplicate input values have been supplied.