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))))
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).
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.
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.
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))))
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))
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With