[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Function that changes value of a variable
From: |
Stefan Monnier |
Subject: |
Re: Function that changes value of a variable |
Date: |
Sat, 20 Aug 2022 22:40:15 -0400 |
User-agent: |
Gnus/5.13 (Gnus v5.13) Emacs/29.0.50 (gnu/linux) |
> 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. ]
> 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) ...)
Of course a simpler solution is to do something else, such as:
(setq pingu (my-constrain pingu ...))
so `my-constrain` doesn't need to set any variable any more and can be
a pure function instead.
Stefan