W = evalin('caller','who global') returns an error

The command
evalin('caller','who global')
correctly returns the global variables in the caller workspace, but
W = evalin('caller','who global')
returns the error message
Error: illegal use of the reserved keyword global
Yet the syntax of the line that throws the error is consistent with the prescribed use of evalin. Is this a bug? What's the workaround? Thanks

3 件のコメント

Steven Lord
Steven Lord 2020 年 6 月 10 日
That code is basically equivalent to running this code in the caller's workspace.
W = who global
You can't use command form when you want to get an output argument from the function that you're calling.
Walter has shown you one way to perform this call. But in general, both evalin and global are discouraged. Can you say a little more about why your function is reaching up into its caller's workspace and why you're using global variables? We may be able to offer some alternatives.
Leo Simon
Leo Simon 2020 年 6 月 10 日
Thanks Steven, here's an mwe, illustrating how I use the evalin syntax. I have decades of globals scattered all over the place, and backward compatibility means that I need a solution (Walter's works perfectly well). But if you have suggestions about alternatives to my use of evalin, I'd be most interested in hearing them.
function parent
global delta
child('gamma',5,'delta',6);
function child(varargin);
W = evalin('caller','who("global")');
for ii=1:2:numel(varargin);
Variable = varargin{ii};
if ~isempty(strmatch(W,Variable));
disp([ Variable ' is a global variable but you passed it as an argument to varargin; don''t do that']);
keyboard;
end;
end
Walter Roberson
Walter Roberson 2020 年 6 月 10 日
I would disagree on that checking. You want to encourage migration to passing variables as parameters, to reduce the reliance on global variables.

サインインしてコメントする。

 採用された回答

Walter Roberson
Walter Roberson 2020 年 6 月 10 日

0 投票

W = evalin('caller','who("global")')

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeScope Variables and Generate Names についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by