mlock
Locks the running function in memory so that clear does not reset it.
Category: Programming > Functions
Syntax
mlock
Called inside a function file, locks that function.
Description
Persistent variables normally disappear when the function is cleared with clear or clear all. A locked function stays in memory, so its persistent variables survive until munlock is called or the session ends. mlock is valid only inside a function file; call it once, usually at the start.
Use it for state that must outlast a clear, such as a call counter or a cache.
Example
State that survives clear
writelines(["function r = counter()", " mlock;", " persistent n", " if isempty(n), n = 0; end", " n = n + 1; r = n;", "end"], 'counter.m');
counter;
counter;
clear counter
counter
Output
ans = 3
Notes
In MatLivre mlock records the lock, so mislocked reports true, but clear never resets the persistent variables of any function, locked or not.