Test existence of global variable within function?
Mostrar comentarios más antiguos
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 comentario
Gabor
el 26 de En. de 2024
Before going into all this nonsense:
ismember('variable_of_interest', who('global'))
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 3 de Feb. de 2021
ismember('variable_of_interest', who('global'))
4 comentarios
Gabor
el 26 de En. de 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
el 26 de En. de 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
el 26 de En. de 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.
Categorías
Más información sobre Structures en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!