help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Set (global) function argument from inside function


From: Stefan Monnier
Subject: Re: Set (global) function argument from inside function
Date: Sun, 10 Aug 2014 10:38:14 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/24.4.50 (gnu/linux)

>  (defun foo (X)
>    (setq X (+ X 5)))
>
>  (setq Y 2)
>  (message "fooY: %s Y: %s" (foo Y) Y)

> #+results:
> : fooY: 7 Y: 2

IIUC you want to pass a variable by reference.  Elisp does not offer to
pass arguments by reference (contrary to, say, C++).  But just like C,
it lets you construct references and pass them:

  (defun foo (X-ref)
    (setf (gv-deref X-ref) (+ (gv-deref X-ref) 5)))

  (setq Y 2)
  (message "fooY: %s Y: %s" (foo (gv-ref Y)) Y)

Note that gv-ref only exists in Emacs>24.3 and only works with
lexical-binding.

If you only care about global variables (rather than arbitrary "place"s,
such as global vars, local vars, array elements, list elements, ...),
and you want it to work with older Emacsen, you can use the following
instead:

  (defun foo (X-name)
    (set X-name (+ (symbol-value X-name) 5)))

  (setq Y 2)
  (message "fooY: %s Y: %s" (foo 'Y) Y)


-- Stefan




reply via email to

[Prev in Thread] Current Thread [Next in Thread]