如何对传递给函数内部的全局变量进行突变? [英] How to mutate global variable passed to and mutated inside function?

查看:104
本文介绍了如何对传递给函数内部的全局变量进行突变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何从函数内部永久更改全局变量的值,而不使用函数内部的变量名称,即:

I'm wondering how to permanently alter the value of a global variable from inside a function, without using the variable's name inside the function, i.e.:

(defvar *test1* 5)
(defun inctest (x) (incf x))
(inctest *test1*) ;after it runs, *test1* is still 5, not 6

根据:

如果传递给函数的对象是可变的,并且您在函数中对其进行了更改,则更改将对调用者可见,因为调用者和被调用者都将引用同一对象.

if the object passed to a function is mutable and you change it in the function, the changes will be visible to the caller since both the caller and the callee will be referencing the same object.

那不是我在上面做什么吗?

Is that not what I'm doing above?

推荐答案

如果希望inctest是一个函数,则将全局变量的 name 传递给它.

If you want inctest to be a function, pass it the name of the global variable.

(defun inctest (x) (incf (symbol-value x)))
(inctest '*test1*)

这篇关于如何对传递给函数内部的全局变量进行突变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆