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!