Test existence of global variable within function?
古いコメントを表示
Hi, I want to access the status of a variable every where within different function. I created the global variable:
global debugFlag
debugFlag = true;
I create a function idebugging the goal will be to use them when developping other function as:
function output = myawesomefunction(input)
...
doing stuff
...
if isdebugging
fprintf(stuff)
end
...
end
The function I created is this one:
function existing = isdebugging()
%%Check if debugFlag global variable exist and is true
if exist('debugFlag', 'var')
existing = debugFlag;
else
existing = false;
end
end
But this function always return false.
W = evalin('caller','whos');
existing = ismember('debugFlag',[W(:).name])
But this always return true. How can I achieve the function I want? I am sure other people are achieving this for debugging, what is the proper method to have some debugging information?
Thank you.
1 件のコメント
Gabor
2024 年 1 月 26 日
Before going into all this nonsense:
ismember('variable_of_interest', who('global'))
採用された回答
その他の回答 (1 件)
Walter Roberson
2021 年 2 月 3 日
ismember('variable_of_interest', who('global'))
4 件のコメント
Gabor
2024 年 1 月 26 日
This should be on the top as the one and only normal answer to the question!
Thank you
"This should be on the top as the one and only normal answer to the question!"
Lets try it right now and see how it fails:
global debugFlag
debugFlag = false; % debug state is FALSE!
YourApproachFails()
MyAnswerWorks()
function YourApproachFails()
if ismember('debugFlag',who('global'))
disp('If this displays then your approach does NOT work')
else
disp('Hurrah! Debugging is disabled!')
end
end
function MyAnswerWorks()
global debugFlag % <- you need this!
if ~isempty(debugFlag) && debugFlag
disp('If this displays then my approach does NOT work')
else
disp('Oh, my answer works. Debugging is disabled!')
end
end
Have a think about how you would need to modify your approach to make it work correctly.
Walter Roberson
2024 年 1 月 26 日
ismember('variable_of_interest', who('global'))
detects whether the global variable exists at all, and does not have the side effect of creating the global variable
Stephen23
2024 年 1 月 26 日
"detects whether the global variable exists at all, and does not have the side effect of creating the global variable"
Yes, I am quite aware of that.
The OP makes it clear that they also want to check the value of that global variable. Which this code does not do.
カテゴリ
ヘルプ センター および File Exchange で Structures についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!