Test existence of global variable within function?
Show older comments
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 Comment
Gabor
on 26 Jan 2024
Before going into all this nonsense:
ismember('variable_of_interest', who('global'))
Accepted Answer
More Answers (1)
Walter Roberson
on 3 Feb 2021
ismember('variable_of_interest', who('global'))
4 Comments
Gabor
on 26 Jan 2024
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
on 26 Jan 2024
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
on 26 Jan 2024
"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.
Categories
Find more on Structures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!