详见关键字:persistent
已语句的变量持久的在一个函数内,将在对同一函数的后续调用之间将其内容保留在内存中。持久变量和全局变量之间的区别在于,持久变量在特定函数的作用域中是局部的,在其他地方不可见。
下面的示例使用一个持久变量来创建一个函数,该函数打印它被调用的次数。
function count_calls () persistent calls = 0; printf ("'count_calls' has been called %d times\n", ++calls); endfunction for i = 1:3 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times -| 'count_calls' has been called 3 times
如示例所示,可以使用persistent
语句语句。以下语句都是持久性语句。
persistent a persistent a b persistent c = 2 persistent d = 3 e f = 5
持久变量的行为等价于C中静态变量的行为。
持久变量的一个限制是,函数的输入或输出参数都不能是持久的:
function y = foo () persistent y = 0; # Not allowed! endfunction foo () -| error: can't make function parameter y persistent
与全局变量一样,持久变量只能初始化一次。例如,在执行以下代码之后
persistent pvar = 1 persistent pvar = 2
持久变量的值pvar
是1,而不是2。
如果一个持久变量被语句但没有初始化为特定值,它将包含一个空矩阵。因此,也可以通过检查它是否为空来初始化持久变量,如下例所示。
function count_calls () persistent calls; if (isempty (calls)) calls = 0; endif printf ("'count_calls' has been called %d times\n", ++calls); endfunction
此实现的行为方式与的上一个实现完全相同count_calls
.
持久变量的值一直保存在内存中,直到它被明确清除为止。假设的支持count_calls
保存在磁盘上,我们会得到以下行为。
for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times clear for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 3 times -| 'count_calls' has been called 4 times clear all for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times clear count_calls for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times
也就是说,只有当包含变量的函数被删除时,持久变量才会从内存中删除。请注意,如果函数定义直接输入到Octave提示符中,则persistentvariable将通过简单的clear
命令作为entirefunction定义将从内存中删除。如果即使函数已清除,也不希望从内存中删除持久变量,则应使用mlock
函数(详见函数锁定).
版权所有 © 2024-2025 Octave中文网
ICP备案/许可证号:黑ICP备2024030411号-2