[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Function that changes value of a variable
From: |
wilnerthomas |
Subject: |
Re: Function that changes value of a variable |
Date: |
Sun, 21 Aug 2022 05:31:04 +0200 (CEST) |
Aug 21, 2022, 02:40 by help-gnu-emacs@gnu.org:
>> I am trying to change the value a a variable with the following function,
>> but is not working as intended.
>>
>> (defun constrain (var min-n max-n) "Ensure that value of var is between
>> MIN-N and MAX-N inclusive by constraining." (cond ((< var min-n) (setq
>> var min-n)) ((> var max-n) (setq var max-n)) ((eq var t) (setq var
>> 1)) ((eq var nil) (setq var 0))))
>>
>
> [ Written this way, it's rather illegible. It was probably manged by your
> MUA because it wasn't labeled as "code" or "preformatted text"
> or somesuch. ]
>
This time it should show properly
(defvar pingu 21)
(defun constrain (variable min-n max-n)
"Ensure that value of variable is between MIN-N and MAX-N inclusive by
constraining."
(cond
((< (symbol-value variable) min-n) (set variable min-n))
((> (symbol-value variable) max-n) (set variable max-n))
((eq (symbol-value variable) t) (set variable 1))
((eq (symbol-value variable) nil) (set variable 0))))
(constrain 'pingu 0 8)
>> Have done the following test, but the value stays 21.
>>
>
> Of course, because the call only passes the value of the variable, not
> the variable itself [ and according your your comment in
> https://emacs.stackexchange.com/questions/73192, you know that
> already. ]
>
> Variables aren't first class objects, so you need to use a reference to
> the variable:
>
> (defun my-constrain (varef ...)
> ... (setf (gv-deref varref) ...)
> ...)
>
> You can then pass a reference to your variable with something like:
>
> (my-constrain (gv-ref pingu) ...)
>
Not so great with reference
> Of course a simpler solution is to do something else, such as:
>
> (setq pingu (my-constrain pingu ...))
>
This looks standard, which is good.
> so `my-constrain` doesn't need to set any variable any more and can be
> a pure function instead.
>
> Stefan
>
Have done
(defun constrain (variable min-n max-n)
"Returns value between MIN-N and MAX-N inclusive by constraining."
(cond
((< (symbol-value variable) min-n) min-n)
((> (symbol-value variable) max-n) max-n)
((eq (symbol-value variable) t) 1)
((eq (symbol-value variable) nil) 0) ))
(defvar pingu 21)
(setq pingu (constrain pingu 0 8))
Which gives me
Lisp error: (wrong-type-argument number-or-marker-p nil)
<(nil 0)
(cond ((< (symbol-value variable) min-n) min-n) ((> (symbol-value variable)
max-n) max-n) ((eq (symbol-value variable) t) 1) ((eq (symbol-value variable)
nil) 0))
constrain(nil 0 8)
(setq pingu (constrain pingu 0 8))
(progn (setq pingu (constrain pingu 0 8)))
eval((progn (setq pingu (constrain pingu 0 8))) t)
elisp--eval-last-sexp(nil)
eval-last-sexp(nil)
funcall-interactively(eval-last-sexp nil)
call-interactively(eval-last-sexp nil nil)
command-execute(eval-last-sexp)