Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment local variables in elisp

Tags:

elisp

I am trying to write a loop in elisp which prints the values sequencially.

I have tried the following code to print the sequence from 1.. which does not work. Please point the error in the code.

(let ((inc_variable 0))
  (message "%S" inc_variable)
  (while t (let ((inc_variable (+ inc_variable 1)))
    (message "%S" inc_variable))))
like image 426
Talespin_Kit Avatar asked Jul 28 '11 12:07

Talespin_Kit


People also ask

How do you increment a lisp?

Use the built-in "+" or "-" functions, or their shorthand "1+" or "1-", if you just want to use the result, without modifying the original number (the argument).

How to create global variable in Lisp?

Common Lisp provides two ways to create global variables: DEFVAR and DEFPARAMETER . Both forms take a variable name, an initial value, and an optional documentation string. After it has been DEFVAR ed or DEFPARAMETER ed, the name can be used anywhere to refer to the current binding of the global variable.

What is SETQ in Emacs?

This special form is just like set except that the first argument is quoted automatically, so you don't need to type the quote mark yourself. Also, as an added convenience, setq permits you to set several different variables to different values, all in one expression.


2 Answers

There are two bindings for inc_variable in this code. The outer binding has the value 0 and never changes. Then, each time round the loop, you create a new binding for inc_variable that gets set to one plus the value of the outer binding (which is always 0). So the inner binding gets the value 1 each time.

Remember that let always creates a new binding: if you want to update the value of an existing binding, use setq:

(let ((inc-variable 0))
  (while t 
    (message "%S" inc-variable)
    (setq inc-variable (+ inc-variable 1))))
like image 199
Gareth Rees Avatar answered Nov 13 '22 00:11

Gareth Rees


Another way to increment variable is to use cl-incf from cl-lib:

(require 'cl-lib)
(let ((x 0))
  (cl-incf x)
  (message "%d" x)
)

The loop might look like this:

(require 'cl-lib)
(let ((x 0))
  (while (< x 10) (cl-incf x)
         (insert (format "%d\n" x))
  )
)
like image 34
Adobe Avatar answered Nov 13 '22 01:11

Adobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!